class MOBModel extends ObservableModel {
    constructor() {
        super();

        this.data;
        this.databaseCategory = "MOB";
        this.hasDR = true;
        this.history = new Array();

        this.init();
    }

    get MOBClosure() {
        return (this.data.closure === '1' || this.data.closure === 'true');
    }
    set MOBClosure(closure) {
        this.data.closure = closure;
    }

    get MOBClosureTime() {
        return parseInt(this.data.timer);
    }
    set MOBClosureTime(timer) {
        this.data.timer = timer;
    }

    get MOBMode() {
        return this.data.position;
    }
    set MOBMode(mode) {
        this.data.position = mode;
    }

    init() {
        var async = new Array();
        var self = this;

        var defaults = {
            closure: "",
            position: "gps",
            timer: "10.0"
        }
        self.data = defaults;

        async.push(readSection("MOB").done(function(section) {
            self.data = $.extend(self.data, JSON.parse(section));
        }));

        async.push(readSection("MOB History").done(function(section) {
            var MOBHistory = JSON.parse(section);

            if (MOBHistory.timestamp !== undefined && MOBHistory.latitude !== undefined
                && MOBHistory.longitude !== undefined && MOBHistory.mobsource !== undefined)
            {
                var MOBTimestamp = MOBHistory.timestamp.split(',');
                var MOBLatitude = MOBHistory.latitude.split(',');
                var MOBLongitude = MOBHistory.longitude.split(',');
                var MOBSource = MOBHistory.mobsource.split(',');
                var numAlarms = Math.max(MOBTimestamp.length, MOBLatitude.length,
                    MOBLongitude.length, MOBSource.length);

                for (var i = 0; i < numAlarms; i++) {
                    self.history.push({
                        'timestamp': MOBTimestamp[i],
                        'latitude': MOBLatitude[i],
                        'longitude': MOBLongitude[i],
                        'source': MOBSource[i]
                    });
                }
            }
        }));

        async.push(readSingle("SpeedInput", "UseGPS").done(function(useCOG) {
            if (useCOG || useCOG === "true") {
                self.hasDR = false;
            }
        }));

        $.when.apply($, async).then(function() {
            self.notifyAll();
        });
    }

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

        databaseArray.push({ section: "MOB", key: "Closure", value: self.data.closure });
        databaseArray.push({ section: "MOB", key: "Position", value: self.data.position });
        databaseArray.push({ section: "MOB", key: "Timer", value: self.data.timer });

        return writeToDatabase(databaseArray, self.databaseCategory);
    }
}

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

    changeClosureEnable(e) {
        this.model.MOBClosure = $(e.target).is(':checked');
    }

    changeClosureTime(e) {
        if (validateRange( $(e.target), 0 , 0, Number.MAX_SAFE_INTEGER, 30)) {
            this.model.MOBClosureTime = $(e.target).val();
        }
    }

    changeMOBMode(e) {
        this.model.MOBMode = $(e.target).val();
    }

    resetMOB() {
		$.ajax( {
			url: 'helpers.php',
			type: 'POST',
			data: {
				'action': 'queryProcessor',
				'query': 'MOB=reset'
			}
		});
    }

    testMOB(e) {
        if ($(e.target).html() === "Test MOB") {
            $(e.target).html("Clear MOB");
            $.ajax( {
				url: 'helpers.php',
				type: 'POST',
				data: {
					'action': 'queryProcessor',
					'query': 'MOB=start'
                }
            });
            $('.MOB-warning').show();
        } else {
            $(e.target).html("Test MOB");
            $.ajax( {
				url: 'helpers.php',
				type: 'POST',
				data: {
					'action': 'queryProcessor',
					'query': 'MOB=stop'
				}
            });
            $('.MOB-warning').hide();
        }
    }

    updateMOB() {
        var isMOBActive = (sessionStorage.getItem('MOBActive') === 'true');
        if (isMOBActive) {
            $('#mob-test').html("Clear MOB");
        } else {
            $('#mob-test').html("Test MOB");
        }
    }
}

class MOBView extends BasicView {
    constructor(controller) {
        super(controller);
    }

    bindEvents() {
        super.bindEvents();

        $('#mob-closure-active').on('change', this.controller.changeClosureEnable.bind(this.controller));
        $('#mob-closure-time').on('change', this.controller.changeClosureTime.bind(this.controller));
        $('[name="mob-mode"]').on('change', this.controller.changeMOBMode.bind(this.controller));
        $('#mob-reset').on('click', this.controller.resetMOB.bind(this.controller));
        $('#mob-test').on('click', this.controller.testMOB.bind(this.controller));
        $(document).on('MOB-update', this.controller.updateMOB.bind(this.controller));
    }

    update(model) {
        var isMOBActive = (sessionStorage.getItem('MOBActive') === 'true');
        if (isMOBActive) {
            $('#mob-test').html("Clear MOB");
        }

        $('#mob-closure-active').prop('checked', model.MOBClosure);
        $('#mob-closure-time').val(model.MOBClosureTime);
        $('[name="mob-mode"][value="' + model.MOBMode + '"]').prop('checked', true);
        if (!model.hasDR) {
            $('#mob-dr').prop('disabled', true);
            $('#mob-dr').parent().css('color', '#bbb');
        }

        $('#mob-history').empty();
        $('#mob-history').append(
                '<tr>'
            +       '<th>Date/Time (UT)</th>'
            +       '<th>Latitude</th>'
            +       '<th>Longitude</th>'
            +       '<th>Source</th>'
            +   '</tr>'
        );

        for (var i = 0; i < model.history.length; i++) {
            var date = new Date(model.history[i].timestamp * 1000);
            $('#mob-history').append(
                    '<tr>'
                +       '<td>' + date.toLocaleString('default', { weekday: "short", year: "numeric",
                            month: "long", day: "numeric", hour12: false, hour: "numeric",
                            minute: "numeric", second: "numeric" }) + '</td>'
                +       '<td>' + decimalDegreesToDecimalMinutes(model.history[i].latitude, "Latitude") + '</td>'
                +       '<td>' + decimalDegreesToDecimalMinutes(model.history[i].longitude, "Longitude") + '</td>'
                +       '<td>' + model.history[i].source + '</td>'
                +   '</tr>'
            );
        }
    }
}