import Ajax from '../ajax.js'
import { alertSuccessMessage } from '../alerts/sweetAlert.js'
import ClassSelect from '../select2.js'
class MaquinaTareaForm {
    /**
     * 
     * @param {*} domItem jQuery item of the form html element 
     */
    constructor(domItem) {
        this.item = domItem
        this.btnNew = this.item.find("#btn-new-maquina-tarea")
        this.btnUpdate = this.item.find("#btn-update-maquina-tarea")
        this.btnComeBack = this.item.find("#btn-come-back")

    }
    init() {
        this.modelId = this.item.data('id')
        this.uri = `/configuracion/maquina-tareas/${this.modelId}`
        this.uriUpdate = `/configuracion/maquina-tareas/update/${this.modelId}`
        this.uriPost = `/configuracion/maquina-tareas`
        this.btnNew.on("click", this.handlePost.bind(this))
        this.btnUpdate.on("click", this.handlePut.bind(this))
        this.handleGet()
        this.btnUpdate.removeClass("d-none")
        this.btnComeBack.removeClass("d-none")

    }
    initNew(){
        this.uri = `/configuracion/maquina-tareas`
        this.btnNew.on("click", this.handlePost.bind(this))
        this.btnNew.removeClass("d-none")  
    }
    handleGet() {
        const ajax = new Ajax(
            this.uri,
            null,
            null,
            this.handleGetSuccess.bind(this),
            this.handleGetError.bind(this)
        )
        ajax.get()
    }
    handleGetSuccess(data) {
        this.item.find('[name="name"]').val(data.name)
        this.item.find('[name="description"]').val(data.description)

    }
    handleGetError(e) {
        console.error(e)
    }
    handlePost() {
        let bodyData = this.getFormData()
        const ajax = new Ajax(
            this.uriPost,
            bodyData,
            null,
            this.handlePostSuccess.bind(this),
            this.handlePostError.bind(this)
        )
        ajax.post()
    }
    handlePostSuccess(data) {
        alertSuccessMessage(data.message)
        $("#modalNewMaquinaTarea").modal('toggle')
    }
    handlePostError() { }
    handlePut() {
        let bodyData = this.getFormData()
        const ajax = new Ajax(
            this.uriUpdate,
            bodyData,
            null,
            this.handlePutSuccess.bind(this),
            this.handlePutError.bind(this)
        )
        ajax.post()
    }
    handlePutSuccess(data) {
        // this.item.reset()
        alertSuccessMessage(data.message)
        this.handleGet(data)
    }
    handlePutError() { }

    getFormData() {
        let data = {}
        this.item.serializeArray().forEach((e) => {
            data[e.name] = e.value
        }
        )
        return data
    }
}
export default MaquinaTareaForm