import Ajax from '../ajax.js'
import ImposicionEsquemaDrawing from '../imposicionEsquemaDrawing.js';

class ImposicionEsquemaForm {
    constructor(domItem) {
        this.item = domItem
        if ($("#imposicion-esquema-drawing").length > 0) {

            this.drawing = new ImposicionEsquemaDrawing($("#imposicion-esquema-drawing"))
        } else {
            this.drawing = null
        }
        this.modelId = this.item.data("id");
        this.btnSubmitUpdateImposicion = this.item.find("#btnSubmitUpdateImposicionEsquema")
        this.btnSubmitNewImposicion = this.item.find("#btnSubmitNewImposicionEsquema")
        this.initialData = {
            "name": null,
            "rows": null,
            "columns": null,
            "rotativa": null,
            "orientacion": null,
            "cosido": null,
            "svg_schema": null,

        }
        this.formData = this.initialData
    }
    load(status = false) {
        if (status) {
            Notiflix.Block.circle('.section-block');
        } else {
            Notiflix.Block.remove('.section-block');
        }

    }
    init() {
        if (this.drawing) {
            this.drawing.setOrientation($("#esquema-orientacion").val())
            this.item.on("change", "#esquema-rows", (event) => {
                let rows = $(event.currentTarget).val()
                this.drawing.setRows(rows)
            })
            this.item.on("change", "#esquema-rotativa", (event) => {
                let rotativa = $(event.currentTarget).prop("checked")
                this.drawing.setRotativa(rotativa)
            })
            this.item.on("change", "#esquema-cosido", (event) => {
                let cosido = $(event.currentTarget).prop("checked")
                this.drawing.setCosido(cosido)
            })
            this.item.on("change", "#esquema-orientacion", (event) => {
                let orientation = $(event.currentTarget).val()
                this.drawing.setOrientation(orientation)
            })
            this.item.on("change", "#esquema-columns", (event) => {
                let columns = $(event.currentTarget).val()
                this.drawing.setColumns(columns)
            })
            if (this.modelId) {
                this.btnSubmitUpdateImposicion.on("click", this.handleUpdate.bind(this))
                this.handleGetData()
            } else {
                this.initNew()
            }
        }
    }
    initNew() {
        this.btnSubmitUpdateImposicion.on("click", this.handleNew.bind(this))
    }
    handleGetData() {
        this.load(true)
        let ajax = new Ajax(`/imposiciones/esquema/find/${this.modelId}`, null, null, this.handleGetDataSuccess.bind(this), this.handleGetDataError.bind(this))
        if (this.modelId) {
            ajax.get()
        } else {
            this.load(false)
        }

    }
    getFormData() {
        let data = {}
        this.item.serializeArray().forEach((e) => {
            let input = this.item.find(`input[name=${e.name}]`)
            if (input) {
                if (input.attr("type") != "checkbox") {
                    data[e.name] = e.value
                }
            }
        }
        )
        this.formData = data
        this.formData["svg_schema"] = this.drawing.getSVG()
        this.formData["rotativa"] = this.drawing.rotativa == true ? 1 : 0;
        this.formData["cosido"] = this.drawing.cosido == true ? 1 : 0;


        return this.formData
    }
    setFormData(data) {
        this.drawing.rows = data.rows
        this.drawing.columns = data.columns
        this.drawing.rotativa = data.rotativa
        this.drawing.cosido = data.cosido
        this.drawing.drawSchema()
        Object.entries(data).forEach(([key, value], index) => {
            let input = this.item.find(`input[name=${key}]`)
            if (input) {

                if (input.attr("type") == "checkbox") {
                    this.item.find(`input[name=${key}]`).prop("checked", value)
                } else {
                    this.item.find(`input[name=${key}]`).val(value)
                }
            }
            this.item.find(`select[name=${key}]`).val(value)

        })

    }
    disable() {
        Object.entries(this.initialData).forEach(([key, value], index) => {
            this.item.find(`input[name=${key}]`).prop("disabled", "disabled")
            this.item.find(`select[name=${key}]`).prop("disabled", "disabled")
        })
    }
    handleGetDataSuccess(response) {
        this.setFormData(response)
        this.load(false)
    }
    handleGetDataError() { }
    handleNew() {
        this.load(true)
        let ajax = new Ajax(`/imposiciones/esquema/create`, this.getFormData(), null, this.postSuccessNew.bind(this), this.postErrorNew.bind(this))
        ajax.post()
    }
    handleUpdate() {
        this.load(true)
        let ajax = new Ajax(`/imposiciones/esquema/${this.modelId}`, this.getFormData(), null, this.postSuccess.bind(this), this.postError.bind(this))
        ajax.post()
    }
    handleDelete(id) {
        let ajax = new Ajax(`/imposiciones/esquema/${id}`, null, null, this.deleteSuccess.bind(this), this.deleteError.bind(this))
        ajax.delete()
    }
    deleteSuccess(response) {
        popSuccessAlert(response.message)
    }
    deleteError(error) {
        popErrorAlert(error.responseJSON.message)
    }
    postSuccess(response) {
        this.load(false)
        this.setFormData(response.data)
        popSuccessAlert(response.message)
    }

    postError(error) {
        this.load(false)
        popErrorAlert(error.responseJSON.message)
        this.validationErrors(error.responseJSON.errors)
    }
    postSuccessNew(response) {
        this.load(false)
        this.disable()
        this.item.find(".invalid-feedback").remove()
        this.btnSubmitNewImposicion.addClass("d-none")
        this.btnSubmitUpdateImposicion.addClass("d-none")
        popSuccessAlert(response.message)
    }
    postErrorNew(error) {
        this.load(false)
        this.validationErrors(error.responseJSON.errors)
        popErrorAlert(error.responseJSON.message)
    }
    validationErrors(errors) {
        this.item.find(".invalid-feedback").remove()
        Object.entries(errors).forEach(([key, value], index) => {
            let el = this.item.find(`input[name=${key}]`)
            this.addError(el, value)
        })
    }
    addError(el, error) {
        el.addClass("is-invalid")
        el.parent().append(`<div class="invalid-feedback">${error}</div>`)
    }
}

export default ImposicionEsquemaForm;