"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModelUpdate = void 0;
const ModelObject_1 = require("./ModelObject");
class ModelUpdate extends ModelObject_1.ModelObject {
    constructor(req, res) {
        super(req, res);
        this.type = "UPDATE";
    }
    prepare(fields) {
        var ret = true;
        console.log(this.req.query);
        console.log(this.req.body);
        if (this.table.length < 1 || this.table == null) {
            console.log("Table is not defined properly.");
            return false;
        }
        let tmpdata = {}, tmp = {};
        if (this.req.body.hasOwnProperty('data')) {
            try {
                tmpdata = JSON.parse(this.req.body.data);
            }
            catch (e) {
                tmpdata = this.req.body.data;
            }
        }
        else {
            console.log("Data is not found into the request");
            return false;
        }
        fields.forEach((element) => {
            if (tmpdata.hasOwnProperty(element)) {
                tmp[element] = tmpdata[element];
            }
        });
        this.nonquery.data = tmp;
        if (this.req.query.hasOwnProperty('filter')) {
            if (this._isfilter) {
                let tmpdata;
                try {
                    let tmp = this.req.query.filter;
                    tmpdata = JSON.parse(tmp);
                }
                catch (e) {
                    tmpdata = this.req.query.filter;
                }
                console.log(tmpdata);
                this.nonquery.filter = Object.assign(tmpdata, this._filter);
                this.nonquery.isfilter = true;
            }
            else {
                this.nonquery.filter = JSON.parse(this.req.params.filter);
                this.nonquery.isfilter = true;
            }
        }
        else {
            if (this.req.query.hasOwnProperty('id')) {
                if (this._isfilter) {
                    this.nonquery.filter = Object.assign({ id: this.req.query.id }, this._filter);
                    this.nonquery.isfilter = true;
                }
                else {
                    this.nonquery.filter = { id: this.req.query.id };
                    this.nonquery.isfilter = true;
                }
            }
            else {
                if (this._isfilter) {
                    this.nonquery.filter = this._filter;
                    this.nonquery.isfilter = true;
                }
                else {
                    ret = false;
                }
            }
        }
        return ret;
    }
    execute(callback) {
        this.log.Debug("Calling uPDATE function in ModelObject.");
        this.nonquery.prepare();
        this.nonquery.Execute((err, data) => {
            this.respond(err, data, callback);
        });
    }
}
exports.ModelUpdate = ModelUpdate;
