"use strict";
this.name = "VimanaX_Alerts";
this.author = "Gnievmir, phkb";
this.license = "CC-BY-NC-SA 3.0";

this._alertTimer = null;		//store pointer to graphical info timer
this._lastAlert = [];
this._disabled = false;
this._seq = 0;
this._flip = false;
this._combatMFD = null;
this._resetCounter = 0;
this._warningOn = false;

this._alerts = [
    ["vx_clean.png", "", "", ""],                                   //0 -no alert
    ["vx_d_missile.png", "DANGER!", "INCOMING MISSILE", ""],        //1 
    ["vx_d_altitude.png", "DANGER!", "ALTITUDE", "TOO LOW"],        //2
    ["vx_d_temp.png", "DANGER!", "TEMPERATURE", "CRITICAL LEVEL"],  //3
    ["vx_d_energy.png", "DANGER!", "ENERGY", "CRITICAL LEVEL"],     //4 
    ["vx_d_shield.png", "DANGER!", "SHIELD", "CRITICAL LEVEL"],     //5 
    ["vx_w_energy.png", "WARNING!", "ENERGY", "LOW LEVEL"],         //6
    ["vx_w_shield.png", "WARNING!", "SHIELD", "LOW LEVEL"],         //7
    ["vx_w_temp.png", "WARNING!", "TEMPERATURE", "TOO HIGH"],       //8 
    ["vx_w_fuelleak.png", "WARNING!", "FUEL LEAK", "DETECTED"]       //9
];

this._operationalFunctionNames = [ // list of functions to enable/disable at HUDSelector callback
    "shipAttackedWithMissile",
    "shipWillLaunchFromStation",
    "shipWillDockWithStation",
    "shipDied"
];

//----------------------------------------------------------------------------------------
this.shipAttackedWithMissile = function (missile, whom) {
    var p = player.ship;
    p._incomingMiss = true;
    if (this._lastAlert[0] != 1) this._lastAlert[0] = -1;
    this.$display(1);
	if (p) p._missiles.push(missile);
}

//----------------------------------------------------------------------------------------
this.shipExitedWitchspace = function() {
	if (player.ship._missiles) {
		player.ship._missiles.length = 0;
	} else {
		player.ship._missiles = [];
	}
}

//----------------------------------------------------------------------------------------
this.shipWillLaunchFromStation = function () {
    this._seq = 0;
    this.shipExitedWitchspace(); // make sure the missiles array is reset and present
    if (!this._alertTimer) this._alertTimer = new Timer(this, this.$alerts.bind(this), 0, 0.5);
    this.$resetAlerts();
}

//----------------------------------------------------------------------------------------
this.shipWillDockWithStation = function () {
    var p = player.ship;
    if (!p || !p.isValid) return;
   
    if (this._alertTimer) {
        this._alertTimer.stop();
        delete this._alertTimer;
    }
    p.setCustomHUDDial("VimanaX_Alert", this._alerts[0][0]);
    p.setCustomHUDDial("VimanaX_AlertText1_Red", "");
    p.setCustomHUDDial("VimanaX_AlertText2_Red", "");
    p.setCustomHUDDial("VimanaX_AlertText3_Red", "");
    p.setCustomHUDDial("VimanaX_AlertText1_Orange", "");
    p.setCustomHUDDial("VimanaX_AlertText2_Orange", "");
    p.setCustomHUDDial("VimanaX_AlertText3_Orange", "");
    p._missiles.length = 0;    
}

//----------------------------------------------------------------------------------------
this.shipDied = function (whom, why) {
    this.shipWillDockWithStation();
}

//----------------------------------------------------------------------------------------
this.$resetAlerts = function () {
    for (let i = 1; i < 5; i++) {
        this._lastAlert[i] = 100000;
    }
    this._lastAlert[5] = 0;
    this._lastAlert[6] = 0;
    player.ship._incomingMiss = false;
    /*this._incomingMiss = false;
	// reset the missile monitoring array
    var p = player.ship;
	if (p._missiles) p._missiles = [];
	p._missiles.length = 0;*/
}

//----------------------------------------------------------------------------------------
this.$alerts = function _vimanaXAlerts_alerts() {
    var that = _vimanaXAlerts_alerts;
    var _p = (that._p = that._p || player.ship);
    var _cbtMFD = (that._cbtMFD = that._cbtMFD || this._combatMFD);
    var _incMissiles = (that._incMissiles = that._incMissiles || this.$checkForIncomingMissiles);
    if (!_p || !_p.isValid) return;
    
    var ano = 0;
    //check incoming missile
    _incMissiles();

    // use combat MFD's value for alt
    var altRaw = _cbtMFD.$Data["combatAlt"].toString();
    var alt = parseInt(altRaw);
    if (isNaN(alt)) {
        alt = 999999;
    } else {
        if (altRaw.indexOf("Mkm") > 0) alt = 999999; // basically max dist
        else if (altRaw.indexOf("km") > 0) alt *= 1000 // convert to meters
    }

    if (_p.energy < _p.maxEnergy / 3 && _p.energy < this._lastAlert[1]) {
        ano = 4;
        this._lastAlert[1] = _p.energy;
    } else if (_p.forwardShield < _p.maxForwardShield * 0.2 && _p.forwardShield < this._lastAlert[2]) {
        ano = 5;
        this._lastAlert[2] = _p.forwardShield;
    } else if (_p.aftShield < _p.maxAftShield * 0.2 && _p.aftShield < this._lastAlert[3]) {
        ano = 5;
        this._lastAlert[3] = _p.aftShield;
    } else if (alt < 10000 && alt < this._lastAlert[4]) {
        ano = 2;
        this._lastAlert[4] = alt;
    } else if (_p.temperature > 0.7 && _p.temperature > this._lastAlert[5]) {
        ano = 3;
        this._lastAlert[5] = _p.temperature;
    } else if (_p.energy < _p.maxEnergy / 2 && _p.energy < this._lastAlert[1]) {
        ano = 6;
        this._lastAlert[1] = _p.energy;
    } else if (!_p.torusEngaged && _p.forwardShield < _p.maxForwardShield / 2 && _p.forwardShield < this._lastAlert[2]) {
        ano = 7;
        this._lastAlert[2] = _p.forwardShield;
    } else if (!_p.torusEngaged && _p.aftShield < _p.maxAftShield / 2 && _p.aftShield < this._lastAlert[3]) {
        ano = 7;
        this._lastAlert[3] = _p.aftShield;
    } else if (_p.temperature > 0.5 && _p.temperature > this._lastAlert[5]) {
        ano = 8;
        this._lastAlert[5] = _p.temperature;
    } else if (_p.fuelLeakRate > 0 && _p.fuel > 0) {
        ano = 9;
    }
    this.$display(ano);
}

//-------------------------------------------------------------------------------------------------------------
// performs a scan of the missile array to see if any are still tracking the player
this.$checkForIncomingMissiles = function _vimanaXAlerts_checkForIncomingMissiles() {
	var p = player.ship;
	// do we have any missiles in the queue?
	if (p._missiles.length === 0) {
		p._incomingMiss = false;
		return;
	}
	// are they in range and valid?
    p._incomingMiss = false; // reset it here, so it can be set if a valid missile is found
	var ml = p._missiles.length;
	while (ml--) {
		var m = p._missiles[ml];
		if (m.isValid && m.isInSpace && m.position.distanceTo(p) < p.scannerRange) {
			p._incomingMiss = true;
			break;
		}
	}
}

//----------------------------------------------------------------------------------------
this.$display = function _vimanaXAlerts_display(a) {
    if (a == 0 && a == this._lastAlert[0]) {
        this._resetCounter = (this._resetCounter + 1) % 4;
        // if we're getting here on every pulse, and a warning message is on, better remove it.
        if (this._resetCounter > 2 && this._warningOn == true) this.$removeAlertDisplay();
        this.$resetAlerts();
        return;
    }
    this._resetCounter = 0;
    var p = player.ship;
    if (a > 0) { //alerts
        this._seq = (this._seq + 1) % 3;
        if (this._seq < 2) {
            this._flip = false;
            if (this._disabled == false) { // we're just disabling the display of the alert, not any of the calcs
                p.setCustomHUDDial("VimanaX_Alert", this._alerts[a][0]);
                if (this._alerts[a][0].indexOf("_d_") >= 0) {
                    p.setCustomHUDDial("VimanaX_AlertText1_Red", this._alerts[a][1]);
                    p.setCustomHUDDial("VimanaX_AlertText2_Red", this._alerts[a][2]);
                    p.setCustomHUDDial("VimanaX_AlertText3_Red", this._alerts[a][3]);
                    p.setCustomHUDDial("VimanaX_AlertText1_Orange", "");
                    p.setCustomHUDDial("VimanaX_AlertText2_Orange", "");
                    p.setCustomHUDDial("VimanaX_AlertText3_Orange", "");
                } else {
                    p.setCustomHUDDial("VimanaX_AlertText1_Red", "");
                    p.setCustomHUDDial("VimanaX_AlertText2_Red", "");
                    p.setCustomHUDDial("VimanaX_AlertText3_Red", "");
                    p.setCustomHUDDial("VimanaX_AlertText1_Orange", this._alerts[a][1]);
                    p.setCustomHUDDial("VimanaX_AlertText2_Orange", this._alerts[a][2]);
                    p.setCustomHUDDial("VimanaX_AlertText3_Orange", this._alerts[a][3]);
                }
                this._warningOn = true;
            }
        } else {
            this.$removeAlertDisplay();
        }
    } else {
        if (this._flip) this.$removeAlertDisplay();
        this._flip = !this._flip;
    }
    this._lastAlert[0] = a;
}

//----------------------------------------------------------------------------------------
this.$removeAlertDisplay = function _vimanaXAlerts_removeAlertDisplay() {
    var p = player.ship;
    p.setCustomHUDDial("VimanaX_Alert", this._alerts[0][0]);
    p.setCustomHUDDial("VimanaX_AlertText1_Red", this._alerts[0][1]);
    p.setCustomHUDDial("VimanaX_AlertText2_Red", this._alerts[0][2]);
    p.setCustomHUDDial("VimanaX_AlertText3_Red", this._alerts[0][3]);
    p.setCustomHUDDial("VimanaX_AlertText1_Orange", this._alerts[0][1]);
    p.setCustomHUDDial("VimanaX_AlertText2_Orange", this._alerts[0][2]);
    p.setCustomHUDDial("VimanaX_AlertText3_Orange", this._alerts[0][3]);
    this._warningOn = false;
}

//----------------------------------------------------------------------------------------
this.$disableAlerts = function _vimanaXAlerts_disableAlerts() {
    if (this._alertTimer && this._alertTimer.isRunning) this._alertTimer.stop();
    var ws = worldScripts.VimanaX_Alerts;
    var funcNames = this._operationalFunctionNames;
    var i = funcNames.length;
    while (i--)
        if (ws[funcNames[i]]) {
            ws["$save_" + funcNames[i]] = ws[funcNames[i]];
            delete ws[funcNames[i]];
        }
}

//----------------------------------------------------------------------------------------
this.$enableAlerts = function _vimanaXAlerts_enableAlerts() {
    var ws = worldScripts.VimanaX_Alerts;
    var funcNames = this._operationalFunctionNames;
    var i = funcNames.length;
    while (i--)
    if (!ws[funcNames[i]]) {
        ws[funcNames[i]] = ws["$save_" + funcNames[i]];
    }
}