/**
 * Data Output MVC controller
 * 
 * 
 * @category    Webserver
 * @package     ATProcessor
 * @author      Sam Meredith <sam@aandtinstruments.com>
 * @version     0.1
 */

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

    // Handle adaptor address change
    adaptorAddressChanged(e) {
        let container = $(e.target).closest('section');
        let idx = parseInt(container.attr('data-connection')) - 1;

        this.model.setAdaptorAddress(idx, $(e.target).val());
    }

    // Create a new connection
    addConnection() {
        if (Object.keys(this.model.savedConnections).length < maxNetworkConnections) {

            this.model.addConnection(defaultConnection);
            this.model.notifyAll();
        } else {
            $('#dialog-text').text("The maximum number of network connections is " + maxNetworkConnections + ".");
            $('#dialog').dialog({
                title: 'Too many connections',
                buttons: {
                    Ok: function() {
                        $(this).dialog("close");
                    }
                }
            }).dialog("open");
        }
    }
    
    // Remove a connection
    closeConnection(e) {
        let self = this;
        let container = $(e.target).closest('section');
        let idx = parseInt(container.attr('data-connection')) - 1;

        $('#dialog-text').text("Are you sure you want to delete I/O connection " + (idx + 1) + ".");
        $('#dialog').dialog({
            title: 'Delete connection?',
            buttons: {
                Yes: function() {
                    container.remove();
                    delete self.model.savedConnections[idx];
                    $(this).dialog("close");
                },
                No: function() {
                    $(this).dialog("close");
                }
            }
        }).dialog("open");
    }

    // Handle connection address change
    connectionAddressChanged(e)
    {
        if ($(e.target).val() === "" || validateIPAddress($(e.target))) {

            let container = $(e.target).closest('section');
            let idx = parseInt(container.attr('data-connection')) - 1;

            this.model.setConnectionAddress(idx, $(e.target).val());

            $(e.target).css('border-color', '');
        }
    }

    connectionNameChanged(e) {

        let container = $(e.target).closest('section');
        let idx = parseInt(container.attr('data-connection')) - 1;

        this.model.setName(idx, $(e.target).val());
    }

    // Handle connection type change
    connectionTypeChanged(e)
    {
        let container = $(e.target).closest('section');
        let idx = parseInt(container.attr('data-connection')) - 1;
 
        this.model.setConnectionType(idx, $(e.target).val());

        // Check if port is still valid
        if ( !this.validatePort(container.find('[name="Port"]'), idx) ) {
            container.find('[name="Port"]').css('border-color', 'red');
        }
    }

    // Handle data format change
    formatChanged(e) {
        let container = $(e.target).closest('section');
        let idx = parseInt($(container).attr('data-connection')) - 1;

        this.model.setFormat(idx, $(e.target).val());
    }

    // Handle output frequency change
    // Removed in favour of a single global output frequency
    frequencyChanged(e) {
        let container = $(e.target).closest('section');
        let idx = parseInt($(container).attr('data-connection')) - 1;

        validateRange($(e.target), 0, 1, 10, 1);
        this.model.setFrequency(idx, $(e.target).val());
    }

    // Handle global output frequency change
    globalFrequencyChanged(e) {

        validateRange($(e.target), 0, 1, 10, 1);
        this.model.outputFrequency = $(e.target).val();
    }

    // Handle port change
    portChanged(e) {
        let container = $(e.target).closest('section');
        let idx = parseInt($(container).attr('data-connection')) - 1;

        validateRange( $(e.target), 0, _MIN_PORT, _MAX_PORT, '');

        if ( this.validatePort($(e.target), idx) ) {
            this.model.setPort(idx, $(e.target).val());
        }
    }

    // Handle Broadcast toggle
    toggleBroadcast(e) {
        let container = $(e.target).closest('section');
        let idx = parseInt($(container).attr('data-connection')) - 1;

        this.model.setBroadcast(idx, $(e.target).is(':checked'));
    }

    // Handle Enable toggle
    toggleEnable(e)
    {
        let container = $(e.target).closest('section');
        let idx = parseInt($(container).attr('data-connection')) - 1;
        
        this.model.setEnabled(idx, $(e.target).is(':checked'));
    }

    // Check for unique type, port combinations
    validatePort($input, idx) {
        let port = $input.val();
        let valid = true;

        for (var connection in this.model.savedConnections) {
            if (this.model.savedConnections.hasOwnProperty(connection)) {
                if ( parseInt(connection) === idx )
                    continue;
                if ( this.model.savedConnections[connection].port === port) {
                    if ( this.model.savedConnections[connection].connectiontype ===
                        this.model.savedConnections[idx].connectiontype ) {
                       valid = false;
                   }
                }
            }
        }

        if (valid) {
            $input.css('border-color', '');
        } else {
            $('#dialog-text').text("Two connections of the same type must use unique ports.");
            $('#dialog').dialog({
                title: 'Invalid Port',
                buttons: {
                    Ok: function() {
                        $(this).dialog("close");
                    }
                }
            }).dialog("open");

            $input.css('border-color', 'red');
        }

        return valid;
    }
}