
var App = Vue.createApp({
    data() {
        return {
            printerList: [],
            printerEditor: {
                id: null,
                name: "",
                density: 203,
                socket_addr: "",
                socket_port: 6101,
                type: "zdl"
            }
        }
    },
    methods: {
        EditPrinter(PrinterID, ShowModal = true)
        {
            let Printer = this.printerList.find((_Printer) => {
                return _Printer.id == PrinterID;
            });

            this.printerEditor.id = Printer.id;
            this.printerEditor.name = Printer.name;
            this.printerEditor.density = Printer.density;
            this.printerEditor.socket_addr = Printer.socket_addr;
            this.printerEditor.socket_port = Printer.socket_port;

            if (ShowModal) {
                $('#printerSettingsModal').modal('show');
            }
        },
        CreatePrinter()
        {
            this.printerEditor.id = null;
            this.printerEditor.name = "";
            this.printerEditor.density = 203;
            this.printerEditor.type = "zdl";
            this.printerEditor.socket_addr = "";
            this.printerEditor.socket_port = 6101;

            $('#printerSettingsModal').modal('show');
        },
        SavePrinter()
        {
            if (this.printerEditor.id == null)
            {
                $.ajax({
                    type: 'POST',
                    url: `/api/printer`,
                    data: JSON.stringify(this.printerEditor),
                    contentType: "application/json"
                }).done(function () {
                    $('#printerSettingsModal').modal('hide');
                    GetPrinterList();
                });
            }
            else
            {
                $.ajax({
                    type: 'PUT',
                    url: `/api/printer`,
                    data: JSON.stringify(this.printerEditor),
                    contentType: "application/json"
                }).done(function () {
                    $('#printerSettingsModal').modal('hide');
                    GetPrinterList();
                });
            }

        },
        DeletePrinter(PrinterID, Confirm = false)
        {
            this.EditPrinter(PrinterID, false);
            
            if (Confirm) {
                $('#printerDeleteModal').modal('hide');

                $.ajax({
                    type: 'DELETE',
                    url: `/api/printer/${PrinterID}`
                }).done(function () {
                    GetPrinterList();
                });
            } else {
                $('#printerDeleteModal').modal('show');
            }
        }
    }
}).mount('main');

function GetPrinterList() {
    $.ajax({
        url: `/api/printers`,
        type: 'GET',
        success: function (Printer) {
            App.printerList = Printer;
        }
    });
}

GetPrinterList();
