"use strict";
this.name = "FuelStation_StationNew";
this.author = "Thargoid";
this.copyright = "Creative Commons: attribution, non-commercial, sharealike with clauses - see readme.txt";
this.description = "Script for fuel station";

this._mySound = null;

//-------------------------------------------------------------------------------------------------------------
this.shipSpawned = function () {
	this.ship.scannerDisplayColor1 = "greenColor";
	this.ship.scannerDisplayColor2 = "lightGrayColor";

	if (worldScripts["FuelStation-Setup"].extraB) {
		var traders = system.shipsWithPrimaryRole("trader", this.ship, 50E3)
		if (traders.length > 0 && traders[0].AIState == "HEAD_FOR_PLANET") {
			traders[0].script.checkFuelStationDistance = this.checkFuelStationDistance; // attach function to script.
			traders[0].script.checkUsage = this.checkUsage; // attach function to script.
			traders[0].setAI("fuelStation_gotoFuelStationAI.plist");
		}
	}

	//  line the station up with the route one. Code borrowed from Anarchies for convenience.
	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.setColour("green");
	this.setPrice();
	this.maxAmount = worldScripts["FuelStation-Setup"].maxStationAmount;
	this.dispensed = 0;
}

//-------------------------------------------------------------------------------------------------------------
this.setColour = function (colName) {
	var rgb = [];
	switch (colName) {
		case "red":
			rgb = [255, 0, 0];
			break;
		case "orange":
			rgb = [255, 106, 0];
			break;
		case "green":
			rgb = [0, 255, 0];
	}
	for (var i = 65; i < this.ship.flashers.length; i++) {
		this.ship.flashers[i].color = rgb;
	}
}

//-------------------------------------------------------------------------------------------------------------
this.setPrice = function () {
	this.fuelPrice = 0.15 * EquipmentInfo.infoForKey("EQ_FUEL").price * player.ship.fuelChargeRate; // price per 0.1LY of fuel
	if (system.economy === 0 || system.economy === 5) { this.fuelPrice *= 1.2; } //  rich industrial or agricultural
	if (system.techLevel > 4 && system.techLevel < 11) { this.fuelPrice *= 1.1; } //  mid-tech level
	this.fuelPrice = this.decPlaces(this.fuelPrice, 2);
}

//-------------------------------------------------------------------------------------------------------------
this.decPlaces = function (number, places) {
	if (!places || places < 0) { places = 0; }
	if (!number) { return 0; }
	return ((Math.round(number * Math.pow(10, places))) / Math.pow(10, places));
}

//-------------------------------------------------------------------------------------------------------------
this.playerDetected = function () {
	if (this.dispensed >= this.maxAmount) {
		if (this.scanTimer && this.scanTimer.isRunning) this.scanTimer.stop();
		return;
	}
	this.firstMessage = true;
	this.fuelTransferred = 0; // how many 0.1LY units are transferred
	this.fuelBill = 0;
	var msg = "Greetings Commander " + player.name + ". Refuel here for only " + this.decPlaces((10 * this.fuelPrice), 1) + " credits per ly.";
	if (this.maxAmount < 7) {
		msg += " Limit of " + this.maxAmount + "ly per ship.";
	}
	this.ship.commsMessage(msg, player.ship);
	if (this.scanTimer) {
		this.scanTimer.start();
	} else {
		this.scanTimer = new Timer(this, this.locatePlayer, 0, 0.50);
	}
}

//-------------------------------------------------------------------------------------------------------------
this.locatePlayer = function locatePlayer() {
	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.$stopSound();
		this.ship.flashers[40].active = true;
		this.playerGone();
		return;
	}
	var p = player.ship;
	var d = this.ship.position.distanceTo(p);

	if (d >= 150 && d < 700) {
		this.setColour("orange");
	}

	if (d < 150) {
		// player ship within 150m of the centre of the fuel station
		if (player.ship.fuel < 7 && this.dispensed < this.maxAmount) {
			if (player.credits > this.fuelBill) {
				// player in place, fuel tank not full and credit balance not empty
				player.ship.fuel += 0.1;
				this.dispensed += 0.1;
				this.fuelBill += this.fuelPrice;
				this.fuelTransferred++;

				if (this.firstMessage) {
					this.$playSound("fuelflow");
					var scr = worldScripts.FuelStation_Facelift;
					this.ship.flashers[40].active = false;
					system.addVisualEffect("fuelStation_alertFX", p.position.add(p.vectorForward.multiply(scr._fxForward)).add(p.vectorUp.multiply(scr._fxUp)));
					player.consoleMessage("Fuel transfer is underway, please come to a halt.", 6);
					this.firstMessage = false;
					this.setColour("red");
				}
				return;
			} else { // not enough funds left
				player.consoleMessage("Insufficient credits remaining, transfer terminated.", 6);
				this.ship.flashers[40].active = true;
				this.setColor("green");
				this.$playSound("fuelshutoff");
				this.scanTimer.stop();
				return;
			}
		} else { // Fuel tank full or max limit reached
			if (player.ship.fuel < 7) {
				player.consoleMessage("Fuel transfer limit reached.", 6);
			} else {
				player.consoleMessage("Fuel tanks are full.", 6);
			}
			this.ship.flashers[40].active = true;
			this.setColour("green");
			this.$playSound("fuelshutoff");
			this.scanTimer.stop();
			return;
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.shipTraversePositiveZ = this.shipTraverseNegativeZ = function (ship) {
	if (ship.isPlayer) this.playerLeaving()
}

//-------------------------------------------------------------------------------------------------------------
this.playerLeaving = function () {
	this.fuelBill = this.decPlaces(this.fuelPrice * this.fuelTransferred, 1);
	player.consoleMessage("Summary - " + (this.fuelTransferred / 10) + " ly transferred, " + this.fuelBill + " credits charged.", 6);
	this.setColour("green");
	player.credits -= this.fuelBill;
	this.fuelTransferred = 0;
	this.fuelBill = 0;
	this.firstMessage = true;
	if (this.maxAmount == 7) this.dispensed = 0;
}

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

//-------------------------------------------------------------------------------------------------------------
this.shipDied = function (whom, why) {
	this.playerGone();
	if (Math.random() < 0.4) {
		this.ship.becomeCascadeExplosion();
	} else {
		this.fuelCount = (Math.ceil(Math.random() * 30) + 30);
		this.ship.spawn("fuelTweaks_burningFuel", this.fuelCount); // lets make this go with a bang!
	}

	if (whom && whom.isPlayer) {
		player.consoleMessage("CCTV beam towards the main station detected.", 6);
		player.score -= 1; // don't condone vandalism!
		player.ship.setBounty(player.bounty + 20, "damaged property");
	}
}

//-------------------------------------------------------------------------------------------------------------
// plays the sound of the fuel being filled
this.$playSound = function $playSound(type) {
	if (this._mySound && this._mySound.isPlaying) this._mySound.stop();
	this._mySound = new SoundSource;
    switch (type) {
        case "fuelflow":
            this._mySound.sound = "fs_fuelflow.ogg";
			this._mySound.loop = true;
            break;
		case "fuelshutoff":
            this._mySound.sound = "fs_fuelshutoff.ogg";
			this._mySound.loop = false;
    }
	this._mySound.play();
}

//-------------------------------------------------------------------------------------------------------------
this.$stopSound = function() {
	if (this._mySound && this._mySound.isPlaying) {
		this._mySound.stop();
	}
	this._mySound = null;
}

//-------------------------------------------------------------------------------------------------------------
// below not used by stationscript but is attached to traderscript.
this.checkFuelStationDistance = function () {
	if (this.ship.position.distanceTo(this.ship.target) > 50E3) {
		this.ship.reactToAIMessage("NEXT_FUELSTATION")
	}
}

//-------------------------------------------------------------------------------------------------------------
this.checkUsage = function () {
	if (this.ship.target.position.distanceTo(player.ship) < 1000) {
		this.ship.reactToAIMessage("NEXT_FUELSTATION")
	} else {
		this.ship.reactToAIMessage("STATION_CLEAR")
	}
}

//-------------------------------------------------------------------------------------------------------------
this.attackedMessage = function () {
	this.ship.commsMessage("ALERT - fuel station under attack, explosion danger!");
}

//-------------------------------------------------------------------------------------------------------------
this.collisionMessage = function () {
	this.ship.commsMessage("ALERT - proximity detection, please take evasive action");
}