/**
 * Model, View, Controller for Leeway page.
 * 
 * Handles display of the calculation for course and
 * allows the user to set a specific leeway constant.
 * 
 * @category    Webserver
 * @package     ATProcessor
 * @author      Cameron Guest <cameron@aandtinstruments.com>
 * @version     0.1
 */

const DEFAULT_LEEWAY_COEFF = 5;

//----------------------------------------
// View
//----------------------------------------
class LeewayView extends BasicView
{
    constructor(controller)
    {
        super(controller);

        this.controller.model.init();
    }

    bindEvents()
    {
        super.bindEvents();
        $(document).on('change', '#leewayCoeff', this.controller.changeLeewayCoeff.bind(this.controller));
    }

    update(model)
    {
        $('#leewayCoeff').val(model.leeway);
    }
}

//----------------------------------------
// Controller
//----------------------------------------
class LeewayController extends BasicController
{
    constructor(model)
    {
        super(model);
    }

    changeLeewayCoeff(e)
    {
        validateRange( $(e.target), 0, -50, 50, 5 );
        this.model.leeway = $(e.target).val();
    }
}

//----------------------------------------
// Model
//----------------------------------------
class LeewayModel extends ObservableModel
{

    //----------------------------------------------
    // Getters and Setters.
    //----------------------------------------------
    set leeway(val) { this.leewayCoeff = val; }
    get leeway() { return this.leewayCoeff; }

    constructor()
    {
        super();
        this.leewayCoeff = DEFAULT_LEEWAY_COEFF;
    }

    init()
    {
        let self = this;

        readSingle('constants', 'leeway').done(function(leeway) {
            self.leewayCoeff = leeway;

            // Set leewayCoeff to a default value, if it cannot be found in the database.
            if (self.leewayCoeff.length === 0)
                self.leewayCoeff = DEFAULT_LEEWAY_COEFF;

            self.notifyAll();
        });
    }

    persistData()
    {
        return writeSingle('constants', 'leeway', this.leewayCoeff, "WindData");
    }
}