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

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);
        if (vehicle.class == 16) mp.game.vehicle.defaultEngineBehaviour = true;
    }
});

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);
        if (veh.class == 16) mp.game.vehicle.defaultEngineBehaviour = false;
    }
});

game.events.onEntityStreamIn((entity: IEntity) => {
    if (!entity) {
        return;
    }

    if (entity && entity.type === EntityType.Vehicle) {
        var data: VehicleData = entity.getSharedData("VehicleData");

        var vehicle = <IVehicle>entity;

        setTimeout(() => setVehicleData(vehicle, data), 1000);
    }
});

function setVehicleData(veh: IVehicle, data: VehicleData): void {
    if (!veh || !game.vehicles.exists(veh)) {
        return;
    }

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

    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 doors = Object.keys(data.Doors);

    doors.forEach(door => {
        var doorNumber = parseInt(door);
        var doorState = <number>data.Doors[doorNumber];

        if (doorState === DoorState.DoorOpen.valueOf()) {
            veh.setDoorOpen(doorNumber, false, false);
        } else if (doorState === DoorState.DoorClosed.valueOf()) {
            veh.setDoorShut(doorNumber, false);
        }
    });

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