"use strict";
this.name = "SpaceBarFaceLift";
this.author = "phkb";
this.description = "Looks after external dock for spacebar";
this.copyright = "2024 phkb";
this.license = "CC BY-NC-SA 4.0";

this._externalDockNotification = false;
this._timer = null;
this._setStation = null;

//----------------------------------------------------------------------------------------
this.systemWillPopulate = function() {
    this._setStation = null;

    system.setPopulator("sb_facelift", {
        callback: function (pos) {
            var w = worldScripts.SpaceBarFaceLift;
            var sp = system.shipsWithRole("random_hits_any_spacebar");
            if (sp && sp.length > 0) w.$registerExternalDocks(sp[0]);
        }.bind(this),
        location: "COORDINATES",
        coordinates: Vector3D(0, 0, 0),
        priority: 500
    });
}

//----------------------------------------------------------------------------------------
// registers our external docks with the eds
this.$registerExternalDocks = function (station) {
	var eds = worldScripts.ExternalDockSystem;
    if (eds) {
        this._setStation = station;

        // set up the timer to let the player know about the docks
        if (this._timer && this._timer.isRunning) this._timer.stop();
        this._timer = new Timer(this, this.$externalDockNotification, 2, 2);
        //log(this.name, "adding external doc for " + station);
        var dve = eds.$addExternalDock({station:station, position:[-550, 0, 22], scale:0.5, preDockCallback:this.$preDockSetup.bind(this)});
        //log(this.name, "dve = " + dve);
    } else {
        // get rid of the flashers on the external dock
        var fa = station.flashers;
        var last = fa.length;
        while (last--) {
            fa[last].remove();
            if (last == 10) break;
        }
    }
}

//----------------------------------------------------------------------------------------
this.$preDockSetup = function(station) {
    // docking at the external port will still get you transferred inside
    player.addMessageToArrivalReport(expandDescription("[spacebar_redocked]"));
}

//----------------------------------------------------------------------------------------
this.$externalDockNotification = function $externalDockNotification() {
	if (this._setStation && this._externalDockNotification == false) {
		if (this._setStation.position.distanceTo(player.ship) < player.ship.scannerRange * 0.85) {
            if (this._setStation.requiresDockingClearance) {
                this._setStation.commsMessage(expandDescription("[spacebar_external_dock_clearance]"), player.ship);
            } else {
                this._setStation.commsMessage(expandDescription("[spacebar_external_dock_free]"), player.ship);
            }
			this._externalDockNotification = true;
		}
	} else {
		this._timer.stop();
	}
}
