import game, { VehicleData } from '../index';
import { IVehicle, EntityType, IEntity, VehicleSeat } from '../game';
import { parseJson } from '../util';

game.events.add('SERVER:Vehicle:UpdateData', (vehId, dataStr) => {
    var data: VehicleData = parseJson(dataStr);
    var vehicle: IVehicle = game.vehicles.at(vehId);

    setVehicleData(vehicle, data);
});

game.events.onPlayerEnterVehicle((vehicle, seat) => {
    while (!game.players.local.inVehicle) {
        game.wait(0);
    }

    if (vehicle) {
        var data: VehicleData = vehicle.getSharedData("VehicleData");

        setVehicleData(vehicle, data);
    }
});

game.events.onPlayerExitVehicle(() => {
    var veh = game.players.local.vehicle;
    while (game.players.local.inVehicle) {
        game.wait(0);
    }

    if (veh) {
        var data: VehicleData = veh.getSharedData("VehicleData");

        setVehicleData(veh, data);
    }
});

game.events.onEntityStreamIn((entity: IEntity) => {
    if (entity && entity.type === EntityType.Vehicle) {
        var data: VehicleData = entity.getSharedData("VehicleData");

        var vehicle = <IVehicle>entity;
        setVehicleData(vehicle, data);
    }
});

function setVehicleData(veh: IVehicle, data: VehicleData): void {
    if (!veh) {
        return;
    }

    if (data === null) {
        data = {
            EngineState: false,
            Locked: false
        };
    }

    var engineState = data.EngineState;
    if (veh.isSeatFree(VehicleSeat.Driver)) {
        veh.setEngineStatus(engineState, true, false);
        veh.setUndriveable(true);
    } else {
        veh.setEngineStatus(engineState, false, true);
        veh.setUndriveable(!engineState);
    }

    var locked: boolean = data.Locked;
    veh.setDoorsLocked(locked);
}