/**
 * Class definitions for Settings page.
 * 
 * @category Webserver
 * @package ATProcessor
 * @author Cameron Guest <cameron@aandtinstruments.com>
 * @version 0.1
 * 
 */

class NetworkAddressModel extends ObservableModel {

    // Getters / Setters 

    get dhcpaddress() { return this.data.dhcpaddress; }
    set dhcpaddress(val) { this.data.dhcpaddress = val; }

    get gateway() { return this.data.gateway; }
    set gateway(val) { this.data.gateway = val; }

    get ipaddress() { return this.data.ipaddress; }
    set ipaddress(val) { this.data.ipaddress = val; }

    get netmask() { return this.data.netmask; }
    set netmask(val) { this.data.netmask = val; }

    get usedhcp() { return this.data.usedhcp; }
    set usedhcp(val) { this.data.usedhcp = val; }

    get internalmac() { return this.data.internalmacaddress; }
    get externalmac() { return this.data.externalmacaddress; }

    constructor() {
        super();
        this.data = {};
        this.addresschanged = false;
        this.init();
    }

    // Initialize values from the DB.
    init() {
        let async = [];
        let self = this;
        let settings;
        let defaults = {
            dhcpaddress: "",
            gateway: "192.168.1.1",
            ipaddress: "192.168.1.219",
            netmask: "255.255.0.0",
            usedhcp: "true",
        }

        async.push(readSection("Settings").done(function(settingJSON) {
            settings = JSON.parse(settingJSON);
        }));

        $.when.apply($, async).then(function() {
            $.extend(self.data, defaults, settings);
            self.notifyAll();
        });
    }

    // Write the data to the DB.
    persistData() {
        let databaseArray = [];

        databaseArray.push( { 'section' : 'Settings', 'key' : "UseDHCP", 'value' : this.usedhcp } );
        databaseArray.push( { 'section' : 'Settings', 'key' : "IPAddress", 'value' : this.ipaddress } );
        databaseArray.push( { 'section' : 'Settings', 'key' : "Netmask", 'value' : this.netmask } );
        databaseArray.push( { 'section' : 'Settings', 'key' : "Gateway", 'value' : this.gateway } );

        return writeToDatabase(databaseArray, 'IPAddress');
    }

}

class NetworkAddressController extends BasicController {

    constructor(model) {
        super(model);
    }

    changeGateway(e) {
        if (validateIPAddress($(e.target))) {
            this.model.addresschanged = true;
            this.model.gateway = $(e.target).val();
        }
    }

    changeIPAddress(e) {
        if (validateIPAddress($(e.target))) {
            this.model.addresschanged = true;
            this.model.ipaddress = $(e.target).val();
        }
    }

    changeIPType(truthy) {
        this.model.addresschanged = true;
        this.model.usedhcp = truthy;
    }

    changeNetmask(e) {
        if (validateNetmask($(e.target))) {
            this.model.addresschanged = true;
            this.model.netmask = $(e.target).val();
        }
    }

    clickApply(e) {
        if (this.model.addresschanged)
            this.showDialog();
        else
            super.clickApply(e);
    }

    clickOK(e) {
        if (this.model.addresschanged)
            this.showDialog();
        else
            super.clickOK(e);
    }

    // Bring up the warning dialog and redirect if a link is supplied.
    showDialog() {
        let self = this;

        // Reset Dialog
        $('#dialog-text').empty();
        $('#progressBar').hide();

        // Setup dialog
        let dialogString = "IP Address Changed.<br><br>";
        if (self.model.usedhcp === "true")
        {
            dialogString += "Use <em>DHCP</em><br>";
            dialogString += "<br>The ATP will restart and request a new address from the DHCP server. This address will be displayed on the LCD screen in the ATP enclosure. Are you sure you want to continue?";
        }
        else
        {
            dialogString += 
                    "<em>Static Address:</em> " + self.model.ipaddress + "<br>"
                +   "<em>Netmask:</em> " + self.model.netmask + "<br>"
                +   "<em>Gateway:</em> " + self.model.gateway + "<br>"
            ;
            dialogString += "<br>The ATP will restart and redirect to the new address. Are you sure you want to continue?";
        }
        $('#dialog-text').html(dialogString);

        $('#dialog').dialog( {
            title: "IP Address Changed",
            buttons: {
                Ok: function(){
                    self.model.persistData().done( function() {
                        //Show progressbar for 5 seconds then redirect to new address
                        $('#dialog-text').text('Restarting Processor...');
                        $('#dialog').dialog( { buttons: {} });
                        $('#progressBar').progressbar({ value: false} ).show();
                        setTimeout( function() {
                            if (self.model.usedhcp === "true") {
                                window.location.href = 'http://' + self.model.dhcpaddress + '/networkAddress.php';
                            } else {
                                window.location.href = 'http://' + self.model.ipaddress + '/networkAddress.php';
                            }
                            $('#dialog').dialog('close');
                        }, 5000);
                    });
                },
                Cancel: function() {
                    $('#dialog').dialog('close');
                    $('#progressBar').hide();
                }
            }
        } ).dialog('open');
    }
}

class NetworkAddressView extends BasicView {

    constructor(controller) {
        super(controller);
    }

    bindEvents() {
        super.bindEvents();
        $('[name="ip-type"]').on('change', this.changeIPType.bind(this));
        $('#ip-address').on('change', this.controller.changeIPAddress.bind(this.controller));
        $('#netmask').on('change', this.controller.changeNetmask.bind(this.controller));
        $('#gateway').on('change', this.controller.changeGateway.bind(this.controller));
    }

    update(model) 
    {
        console.log(model);

        $('#ip-address').val(model.ipaddress);
        $('#netmask').val(model.netmask);
        $('#gateway').val(model.gateway);
        $('#dhcp-address').val(model.dhcpaddress);
        
        $('[name="ip-type"][value="' + model.usedhcp + '"]').prop('checked', true);
        $('[name="ip-field"]').prop('disabled', model.usedhcp == "true");

        $('#internal-mac').text(model.internalmac);
        $('#external-mac').text(model.externalmac);
    }

    // Disable input boxes depending on which address type selected (DHCP / static).
    changeIPType(e) {
        $('[name="ip-field"]').prop('disabled', $(e.target).val() == "true");
        this.controller.changeIPType($(e.target).val());
    }
}