"use strict";
this.name = "ShipConfiguration_SellNegotiate";
this.author = "phkb";
this.copyright = "2016 phkb";
this.description = "Handles the process of selling the rare equipment items (eg cloaking device)";
this.licence = "CC BY-NC-SA 3.0";

this._value = 0;
this._offer = 0;
this._currentMessage = "";
this._extra = "";
this._acceptValues = ["y", "yes", "accept", "sell"];
this._returnValues = ["n", "no", "return", "no sale", "go back", "back", "cancel", "cancel sale"];
this._equipmentKey = "";
this._tries = {};

//-------------------------------------------------------------------------------------------------------------
this.startUpComplete = function () {
	if (worldScripts.ShipConfiguration_Core._disabled) {
		delete this.playerWillSaveGame;
		delete this.shipWillEnterWitchspace;
		delete this.startUpComplete;
		return;
	}
	if (missionVariables.ShipConfig_SellNegotiateTries) {
		// load in any try information
		this._tries = JSON.parse(missionVariables.ShipConfig_SellNegotiateTries);
		delete missionVariables.ShipConfig_SellNegotiateTries;
	}
}

//-------------------------------------------------------------------------------------------------------------
this.playerWillSaveGame = function () {
	// save the tries dictionary so the player can't get save, reload and try again
	missionVariables.ShipConfig_SellNegotiateTries = JSON.stringify(this._tries);
}

//-------------------------------------------------------------------------------------------------------------
this.shipWillEnterWitchspace = function (cause, destination) {
	// reset the tries dictionary
	this._tries = {};
}

//-------------------------------------------------------------------------------------------------------------
this.$displayInitialScreen = function $displayInitialScreen(equipmentKey, baseCost) {
	// work out the maximum value of this item, based on economy and techlevel factors
	this._value = (baseCost +
			((7 - system.economy) / 7) * (baseCost * 0.4) // economy-based factor - higher economy means better price
			+
			(system.techLevel / 14) * (baseCost * 0.8)) // techlevel based factor - higher techlevel means better price
		*
		((system.scrambledPseudoRandomNumber(baseCost) * 0.5) + 0.5); // multiply by a random value between 0.5 and 1, so occasionally item will be offered at less than base cost

	this._offer = baseCost * (system.scrambledPseudoRandomNumber(baseCost) * 0.8);
	if (this._offer < 100 && this._offer > 10) this._offer = parseInt(this._offer / 10) * 10;
	if (this._offer < 1000 && this._offer > 99) this._offer = parseInt(this._offer / 100) * 100;
	if (this._offer > 1000) this._offer = parseInt(this._offer / 1000) * 1000;

	// get the initial message to display to the player
	this._currentMessage = expandDescription("[sc_sellnegotiate_initial]", {
		guess: formatCredits(this._offer, false, true)
	});
	this._extra = expandDescription("[sc_sellnegotiate_confirm]");

	// special notice for the cloaking device - you can't buy it again later if you sell it now
	if (equipmentKey === "EQ_CLOAKING_DEVICE") this._currentMessage += expandDescription("[sc_sellnegotiate_cloakingdevice]");
	// store the equipment key for use later
	this._equipmentKey = equipmentKey;

	// has the player already tried to negotiate a price
	var tries = 0;
	if (this._tries[this._equipmentKey + "_" + player.ship.dockedStation.name]) tries = this._tries[this._equipmentKey + "_" + player.ship.dockedStation.name];
	if (tries >= 3) {
		// if the player has already tried too many times, go straight to the no deal screen
		this.$noDeal();
	} else {
		this.$showScreen();
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$showScreen = function $showScreen() {
	var opts = {
		screenID: "oolite-shipconfig-sellnegotiate-map",
		title: expandDescription("[sc_sellnegotiate_title]"),
		allowInterrupt: false,
		overlay: {
			name: "shipconfig_chat.png",
			height: 546
		},
		exitScreen: "GUI_SCREEN_INTERFACES",
		message: this._currentMessage + expandDescription("[sc_sellnegotiate_additional]", {
			extra_info: (this._offer != 0 ? this._extra : "")
		}),
		textEntry: true
	};
	mission.runScreen(opts, this.$getEstimate, this);
}

//-------------------------------------------------------------------------------------------------------------
this.$getEstimate = function $getEstimate(param) {
	if (param == null) {
		this.$goBack();
		return;
	}
	if (parseInt(param) >= 1 && parseInt(param) <= 9999999) {
		this._offer = 0;
		// is the estimate inside or outside the calculated value
		if (parseInt(param) > (this._value * 1.1)) {
			// check to see how many times we've tried to negotiate a price on this station for this piece of equipment.
			var tries = 0;
			if (this._tries[this._equipmentKey + "_" + player.ship.dockedStation.name]) tries = this._tries[this._equipmentKey + "_" + player.ship.dockedStation.name];
			tries += 1;
			this._tries[this._equipmentKey + "_" + player.ship.dockedStation.name] = tries;
			// if we're tried too many times, give the "No Deal" message
			if (tries >= 3) {
				this.$noDeal();
			} else {
				// otherwise, tell the player their estimate was unreasonable
				this._currentMessage = expandDescription("[sc_sellnegotiate_unreasonable]");
				this.$showScreen();
			}
		} else {
			// OK, it's a deal.
			player.credits += parseInt(param);
			player.ship.removeEquipment(this._equipmentKey);
			worldScripts.ShipConfiguration_Core.$playSound("sell");

			mission.runScreen({
				screenID: "oolite-shipconfig-sellnegotiate-map",
				title: expandDescription("[sc_sellnegotiate_title]"),
				overlay: {
					name: "shipconfig_chat.png",
					height: 546
				},
				message: expandDescription("[sc_sellnegotiate_complete]"),
				allowInterrupt: false,
			}, this.$saleComplete, this);
		}
	} else {
		// check to see if the entered text was one of the "return" values
		if (param === "" || this._returnValues.indexOf(param.toLowerCase()) >= 0) {
			this.$goBack();
			return;
		}
		if (this._acceptValues.indexOf(param.toLowerCase()) >= 0 && this._offer != 0) {
			// OK, it's a deal.
			player.credits += this._offer;
			player.ship.removeEquipment(this._equipmentKey);
			worldScripts.ShipConfiguration_Core.$playSound("sell");

			mission.runScreen({
				screenID: "oolite-shipconfig-sellnegotiate-map",
				title: expandDescription("[sc_sellnegotiate_title]"),
				overlay: {
					name: "shipconfig_chat.png",
					height: 546
				},
				message: expandDescription("[sc_sellnegotiate_complete]"),
				allowInterrupt: false,
			}, this.$saleComplete, this);

			return;
		}
		// otherwise show the "I don't understand" message
		this._offer = 0;
		this._currentMessage = expandDescription("[sc_sellnegotiate_syntax]");
		this.$showScreen();
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$saleComplete = function $saleComplete(choice) {
	this.$goBack();
}

//-------------------------------------------------------------------------------------------------------------
this.$goBack = function $goBack() {
	worldScripts.ShipConfiguration_Core.$sellEquipment();
}

//-------------------------------------------------------------------------------------------------------------
this.$noDeal = function $noDeal() {
	mission.runScreen({
		screenID: "oolite-shipconfig-sellnegotiate-map",
		title: expandDescription("[sc_sellnegotiate_title]"),
		overlay: {
			name: "shipconfig_chat.png",
			height: 546
		},
		message: expandDescription("[sc_sellnegotiate_nodeal]"),
		allowInterrupt: false,
	}, this.$saleComplete, this);
}