/**
 * MVC Nmea Filter Page MVC.
 * 
 * Allows user to setup a filter for incoming and outgoing
 * NMEA connections.
 * 
 * @category Webserver
 * @package ATProcessor
 * @author Sam Meredith <sam@aandtinstruments.com>
 * @version 0.1
 */

class SerialTypeModel extends ObservableModel
{

    constructor()
    {
        super();

        this.serialTypes = [];
        this.mwvMode = 0;
    }

    init()
    {
        let self = this;

        $.when(readSingle("NMEA1", "SerialDataType"), readSingle("NMEA2", "SerialDataType"),
            readSingle("NMEA3", "SerialDataType"), readSingle("NMEA", "Channels"),
            readSingle("NMEA", "MWVOutputType")).done(function(
                nmea1, nmea2, nmea3, channels, mwvMode) {

                let async = [];

                self.serialTypes[0] = { name: "ATP Port 1", type: (nmea1[0] || "NMEA") };
                self.serialTypes[1] = { name: "ATP Port 2", type: (nmea2[0] || "NMEA") };
                self.serialTypes[2] = { name: "ATP Port 3", type: (nmea3[0] || "NMEA") };

                let channelList = channels[0].split(';');
                channelList.forEach(function(instance) {
                    // 0 invalid, 1, 2 and 3 already read
                    let instanceNumber = parseInt(instance);
                    if (instanceNumber > 3) {
                        async.push(readSection("NMEA" + instanceNumber).done(function(nmeaJSON) {
                            let nmeaSection = JSON.parse(nmeaJSON);

                            self.serialTypes[instanceNumber - 1] = {
                                name : (nmeaSection["name"] || "Port " + (instanceNumber - 1)),
                                type: (nmeaSection["serialdatatype"] || "NMEA")
                            }
                        }));
                    }
                });

                self.mwvMode = parseInt(mwvMode[0]);
                
                $.when.apply($, async).then(function() {
                    self.notifyAll();
                });
        });
    }

    persistData()
    {
        var databaseArray = new Array();

        this.serialTypes.forEach(function(value, index) {
            databaseArray.push(
                { 'section': 'NMEA' + (index + 1), 'key': 'SerialDataType', value: (value.type || "NMEA") }
            );
        });

        databaseArray.push({ 'section': 'NMEA', 'key': 'mwvoutputtype', 'value': this.mwvMode });
     
        return writeToDatabase(databaseArray, 'NMEAFilter');
    }
}

class SerialTypeController extends BasicController 
{
    constructor(model)
    {
        super(model);
    }

    changePort(e)
    {
        let port = $(e.target).attr("data-port");

        this.model.serialTypes[port].type = $(e.target).val();
    }

    changeMWVMode(e)
    {
        this.model.mwvMode = $(e.target).attr('id') === "relative" ? 1 : $(e.target).attr('id') === "true" ? 2 : 0;
    }
}

class SerialTypeView extends BasicView
{
    constructor(controller)
    {
        super(controller);

        this.controller.model.init();
    }

    bindEvents()
    {
        super.bindEvents();
        
        $('#serial-type-container').on('change', 'input[type="radio"]', this.controller.changePort.bind(this.controller));
        $('input[name="mwv-mode"]').on('change', this.controller.changeMWVMode.bind(this.controller));
    }

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

        $('#serial-type-container').empty();
        $('#serial-type-container').css('--gridCols', model.serialTypes.filter(Boolean).length.toString());
        let columnIndex = 0;
        model.serialTypes.forEach(function(value, index) {
            ++columnIndex;

            let column = $(
                    '<h2 style="grid-row: 1">' + value.name + '</h2>'
                +   '<div style="grid-row: 2">'
                +       '<input type="radio" value="NMEA" name="port-' + (index + 1) + '" data-port="' + index + '">'
                +       'NMEA0183'
                +   '</div>'
                +   '<div  style="grid-row: 3">'
                +       '<input type="radio" value="Serial" name="port-' + (index + 1) + '" data-port="' + index + '">'
                +       'Serial'
                +   '</div>'
                +   '<div  style="grid-row: 4">'
                +       '<input type="radio" value="MIP" name="port-' + (index + 1) + '" data-port="' + index + '">'
                +       'MIP'
                +   '</div>'
                +   '<div  style="grid-row: 5">'
                +       '<input type="radio" value="DCELL" name="port-' + (index + 1) + '" data-port="' + index + '">'
                +       'DCELL'
                +   '</div>'
            );
            column.each(function(index, value) {
                $(value).css('grid-column', columnIndex.toString());
            });
            column.find('[value="' + value.type + '"]').prop('checked', true);
             $('#serial-type-container').append(column);
        });

        if (model.mwvMode === 1) $('input[name="mwv-mode"][id="relative"]').prop('checked', true);
        else if (model.mwvMode === 2) $('input[name="mwv-mode"][id="true"]').prop('checked', true);
    }
}
