"use strict";
this.name = "VisaStation";
this.author = "Thargoid, phkb";
this.copyright = "Creative Commons: attribution, non-commercial, sharealike with clauses - see readme.txt";
this.description = "Visa Station";
this.version = "1.0";

this._linksAdded = false;

//----------------------------------------------------------------------------------------
this.shipSpawned = function () { //  line the station up with the route one. Code borrowed from Anarchies for convenience.
	this.ship.scannerDisplayColor1 = "greenColor";
	this.ship.scannerDisplayColor2 = "darkGrayColor";

	if (system.isInterstellarSpace || !system.mainPlanet) { return; }
	var targetVector = system.mainPlanet.position.subtract(this.ship.position).direction()
	var angle = this.ship.heading.angleTo(targetVector)
	var cross = this.ship.heading.cross(targetVector).direction()
	this.ship.orientation = this.ship.orientation.rotate(cross, -angle);
	this.setPrice();
}

//----------------------------------------------------------------------------------------
this.addBCCLinks = function() {
    this._linksAdded = true;
    // set up broadcast comms interface
    var bcc = worldScripts.BroadcastCommsMFD;
    if (bcc.$checkMessageExists("visa_24") === false) {
        bcc.$createMessage({
            messageName: "visa_24",
            callbackFunction: this.ship.script.doPurchase.bind(this, 24),
            displayText: "[" + expandMissionText("visa_bcc_item", {time: "24", price: formatCredits(this.visaPrice, false, true)}) + "]",
            messageText: "",
            ship: this.ship,
            transmissionType: "target",
            deleteOnTransmit: false,
            delayCallback: 0,
            hideOnConditionRed: true
        });
    }
    if (bcc.$checkMessageExists("visa_48") === false) {
        bcc.$createMessage({
            messageName: "visa_48",
            callbackFunction: this.ship.script.doPurchase.bind(this, 48),
            displayText: "[" + expandMissionText("visa_bcc_item", {time: "48", price: formatCredits(this.visaPrice * 2, false, true)}) + "]",
            messageText: "",
            ship: this.ship,
            transmissionType: "target",
            deleteOnTransmit: false,
            delayCallback: 0,
            hideOnConditionRed: true
        });
    }
    if (bcc.$checkMessageExists("visa_72") === false) {
        bcc.$createMessage({
            messageName: "visa_72",
            callbackFunction: this.ship.script.doPurchase.bind(this, 72),
            displayText: "[" + expandMissionText("visa_bcc_item", {time: "72", price: formatCredits(this.visaPrice * 3, false, true)}) + "]",
            messageText: "",
            ship: this.ship,
            transmissionType: "target",
            deleteOnTransmit: false,
            delayCallback: 0,
            hideOnConditionRed: true
        });
    }
}

//----------------------------------------------------------------------------------------
this.removeBCCLinks = function() {
    this._linksAdded = false;
    var bcc = worldScripts.BroadcastCommsMFD;
    bcc.$removeMessage("visa_24");
    bcc.$removeMessage("visa_48");
    bcc.$removeMessage("visa_72");
}

//----------------------------------------------------------------------------------------
this.doPurchase = function(time) {
    // don't let the player accidentally do it twice
    if (this._payTimer && this._payTimer.isRunning) return;
    this.$playSound();
    player.consoleMessage(expandMissionText("visa_bcc_initiated", {time: time.toString()}), 4);
    switch (time) {
        case 24: this._payTimer = new Timer(this, this.purchase.bind(this, 24), 4, 0); break;
        case 48: this._payTimer = new Timer(this, this.purchase.bind(this, 48), 4, 0); break;
        case 72: this._payTimer = new Timer(this, this.purchase.bind(this, 72), 4, 0); break;
    }
}

//----------------------------------------------------------------------------------------
this.purchase = function(length) {
    if (player.credits > this.visaPrice) {
        var dip = worldScripts.DayDiplomacy_060_Citizenships;
        player.credits -= this.visaPrice;
        for (var i = 0; i < length / 24; i++) {
            dip._add1DayVisa(system.ID);
        }
        worldScripts.QuickVisa.$updatePF2Docks();
        player.consoleMessage(expandMissionText("visa_bcc_complete", {time: length.toString(), price: formatCredits(this.visaPrice, false, true)}), 6);
    } else {
        player.consoleMessage(expandMissionText("visa_bcc_low_credits"), 6);
    }
    this._payTimer = null;
}

//----------------------------------------------------------------------------------------
this.setPrice = function () {
    this.visaPrice = worldScripts["DayDiplomacy_060_Citizenships"].$getVisaPrice(system.info);
    switch (system.government) {
        case 3: this.visaPrice *= worldScripts.QuickVisa._settings._visaGov3PriceFactor; break
        case 4: this.visaPrice *= worldScripts.QuickVisa._settings._visaGov4PriceFactor; break
        case 7: this.visaPrice *= worldScripts.QuickVisa._settings._visaGov7PriceFactor; break
    }
    this.visaPrice = parseInt(this.visaPrice);
}

//----------------------------------------------------------------------------------------
this.playerDetected = function () {
    if (this.scanTimer && this.scanTimer.isRunning) this.scanTimer.stop();
	if (!this.firstMessage) {
        this.firstMessage = true;
        this.messageTimer = new Timer(this, this.sendInitialMessage.bind(this), 5, 0);
    }
	if (this.scanTimer) {
		this.scanTimer.start();
	} else {
		this.scanTimer = new Timer(this, this.locatePlayer, 0, 0.50);
	}
}

//----------------------------------------------------------------------------------------
this.sendInitialMessage = function() {
    var dip = worldScripts.DayDiplomacy_060_Citizenships;
    if (dip.$hasPlayerCitizenship(galaxyNumber, system.ID)) return;

	var msg = expandMissionText("visa_station_greeting", {price: formatCredits(this.visaPrice, false, true)});
	this.ship.commsMessage(msg, player.ship);
}

//----------------------------------------------------------------------------------------
this.locatePlayer = function () {
	if (!this.ship || !this.ship.isValid || !this.ship.position || !player.ship.isValid) { // if the ship no longer exists but timer is running, e.g. if player has jumped whilst near a satellite into a system without one
		this.playerGone();
		return;
	}

	if (this.ship.position.distanceTo(player.ship.position) < 1000) { // player ship within 1000m of the centre of the satellite
		if (this.firstMessage) {
            this.firstMessage = false;
            // only allow visas to be purchased if the player is not a citizen
            var dip = worldScripts.DayDiplomacy_060_Citizenships;
            if (dip.$hasPlayerCitizenship(galaxyNumber, system.ID)) return;

            player.consoleMessage(expandMissionText("visa_station_helper"), 10);
        }
        this.addBCCLinks();
	} else {
        if (this._linksAdded) this.removeBCCLinks();
    }
}

//----------------------------------------------------------------------------------------
this.playerWillEnterWitchspace = this.playerGone = function () {
	if (this.scanTimer) {
        this.removeBCCLinks();
		this.scanTimer.stop();
		delete this.scanTimer;
	}
}

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

	if (whom && whom.isPlayer) {
		player.consoleMessage(expandMissionText("visa_died_message"), 6);
		player.score -= 1; // don't condone vandalism!
		player.bounty += 20;
	}
}

//----------------------------------------------------------------------------------------
this.attackedMessage = function () {
	this.ship.commsMessage(expandMissionText("visa_station_attacked"));
}

//----------------------------------------------------------------------------------------
this.$playSound = function() {
	var mySound = new SoundSource;
    mySound.sound = "[@click]";
	mySound.loop = false;
	mySound.volume = 0.5;
	mySound.play();
}