var { BaseModel, BaseSecondaryForm } = require('../master/baseModels.js');
import { ApiService } from "../../util/apiService.js";
require('knockout.validation');

export class CompanyInfo extends BaseModel {
    constructor(model, parent) {
        super(model);
        this.fields = ko.observableArray();
        if (_h.any(model.fields))
            for (var j = 0; j < model.fields.length; j++) {
                model.fields[j].formId = model.id;
                this.fields.push(model.fields[j]);
            }
    }
}

export class CompanyInfoDataForm extends BaseSecondaryForm {
    constructor(viewModel, model, lastPriority) {
        super(viewModel, [
            { name: "formId", type: "ob", val: model.formId },
            { name: "id", type: "ob", val: model.id },
            { name: "priority", type: "ob", val: undefined },
            { name: "lastPriority", type: "ob", val: undefined },
            { name: "editMode", type: "ob", val: model.editMode },
            { name: "fields", type: "obar", val: undefined }
        ], model.editMode ? "EditModalCaption" : "CreateModalCaption");
        this.width = "500px";

        if (model.editMode) {
            this.priority(lastPriority + 1);
            this.lastPriority(lastPriority + 1);
        } else {
            this.priority(model.priority);
            this.lastPriority(lastPriority);
        }

        if (_h.any(model.fields))
            for (var j = 0; j < model.fields.length; j++) {
                model.fields[j].formId = model.formId;
                model.fields[j].id = model.id;
                var record = new CompanyFormField(model.fields[j]);
                this.fields.push(record);
            }
        this.setValidationObject();
        this.createForm();
    }

    createForm() {
        const controls = [
            this.createLine({ t: 'tm', templateName: 'companyinfo-fields-form-t' }, undefined, true, 30, 30),
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: 'create', vis: !this.editMode(), click: this.parentVM.create },
                    { name: 'edit', vis: this.editMode, click: this.parentVM.edit },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
    toServer() {
        for (var j = 0; j < this.fields().length; j++) {
            var f = this.fields()[j];
            if (!this.fields()[j].validationObject.isValid()) {
                this.fields()[j].validationObject.errors.showAllMessages();
                return false;
            }
        }

        var model = {
            id: this.id(),
            formId: this.formId(),
            values: []
        };
        for (var j = 0; j < this.fields().length; j++) {
            model.values.push({
                key: this.fields()[j].order(), value: this.fields()[j].value()
            });
        }
        return model;
    }

    setValidationObject() {
        var self = this;
        self.validationObject = ko.validatedObservable({
            fields: self.fields
        });
    }
}
export class CompanyFormField {
    constructor(model) {
        this.id = model.id;
        this.formId = ko.observable(model.formId);
        this.order = ko.observable(model.order);
        this.name = ko.observable(model.name);
        this.fileName = ko.observable(model.fileName);
        this.dataType = ko.observable(model.dataType);
        if (model["value"])
            this.value = ko.observable(model.value());
        else
            this.value = ko.observable(undefined);
        var self = this;
        var obj = {};
        if (model.required || model.dataType === 1) {
            var sub = {};
            if (model.required) {
                sub.required = true;
            }
            if (model.dataType === 1) {
                sub.numberOnly = true;
            }
            obj = {
                value: self.value.extend(sub)
            };
        }
        this.validationObject = ko.validatedObservable(obj);
    }

    handleFileChoose(files) {
        var file = files;
        var ext = _h.getExtension(file.name);

        _h.toBase64(file, function (res) {
            var model = {
                controllerName: 61,
                inputData: {
                    id: this.id,
                    formId: this.formId(),
                    fieldOrder: this.order(),
                    file: res,
                    fileName: file.name,
                    fileType: ext
                }
            };
            ApiService.request(
                {
                    url: "/api/common/postimportfile",
                    data: model,
                    success: function (data) {
                        this.value(file.name);
                    }.bind(this),
                    error: function (data) {
                    }.bind(this)
                });


        }.bind(this));
    }
    removeFile() {
        var model = {
            controllerName: 61,
            inputData: {
                formId: this.formId(),
                id: this.id,
                fieldOrder: this.order(),
                fileName: this.value(),
            }
        };
        ApiService.request(
            {
                url: "/api/common/deletefile",
                data: model,
                success: function (data) {
                    this.value(undefined)
                }.bind(this),
                error: function (data) {
                }.bind(this)
            });
    }
}