import { IEntity, IPlayer, IPlayerPool, IVehicle, IVehiclePool, VehicleSeat, EntityType } from "../../game";
import { parseJson } from "../../util";

class RageEntity implements IEntity {
    private entity: EntityMp;

    get id(): number {
        return this.entity.id;
    }

    constructor(entity: EntityMp) {
        this.entity = entity;
    }

    get type(): EntityType {
        switch (this.entity.type) {
            case 'vehicle': return EntityType.Vehicle;
            case 'player': return EntityType.Player;
            default: return EntityType.Unknown;
        }
    }

    getSharedData<T>(key: string): T {
        var data = this.entity.getVariable(key);
        if (typeof data !== 'undefined') {
            return parseJson<T>(<string>data);
        }

        return null;
    }
}

class RagePlayer extends RageEntity implements IPlayer {
    private player: PlayerMp;

    get name(): string {
        return this.player.name;
    }

    get vehicle(): IVehicle {
        var veh: VehicleMp = this.player.vehicle;
        return veh ? new RageVehicle(veh) : null;
    }

    get inVehicle(): boolean {
        return this.player.isInAnyVehicle(false);
    }

    constructor(player: PlayerMp) {
        super(player);
        this.player = player;
    }
}

class RagePlayerPool implements IPlayerPool {
    get local(): IPlayer {
        return new RagePlayer(mp.players.local);
    }

    at(id: number): IPlayer {
        return new RagePlayer(mp.players.atRemoteId(Number(id)));
    }

    forEach(fn: (entity: IPlayer) => void): void {
        mp.players.forEach(e => {
            fn(new RagePlayer(e));
        });
    }
}

class RageVehicle extends RageEntity implements IVehicle {
    private vehicle: VehicleMp;

    constructor(vehicle: VehicleMp) {
        super(vehicle);
        this.vehicle = vehicle;
    }

    isSeatFree(seat: VehicleSeat): boolean {
        return this.vehicle.isSeatFree(<number>seat - 1);
    }

    setEngineStatus(status: boolean, instantly: boolean, otherwise: boolean) {
        this.vehicle.setEngineOn(status, instantly, otherwise);
    }

    setUndriveable(status: boolean) {
        this.vehicle.setUndriveable(status);
    }

    setDoorsLocked(state: boolean) {
        this.vehicle.setDoorsLocked(state ? 2 : 1);
    }
}

class RageVehiclePool implements IVehiclePool {
    at(id: number): IVehicle {
        return new RageVehicle(mp.vehicles.atRemoteId(Number(id)));
    }

    forEach(fn: (entity: IVehicle) => void): void {
        mp.vehicles.forEach(e => {
            fn(new RageVehicle(e));
        })
    }


}

export {
    RageEntity,
    RagePlayer,
    RagePlayerPool,
    RageVehicle,
    RageVehiclePool,
}
