export default function waypointUtil() {

    let x_saved: number;
    let y_saved: number;
    let z_saved: number;
    let waypointSet: boolean;

    mp.events.add("SERVER:Util_setWaypoint", (x, y) => {
        mp.game.ui.setNewWaypoint(x, y);
    });

    mp.events.add("playerCreateWaypoint", (position) => {
        x_saved = position.x;
        y_saved = position.y;
        z_saved = position.z;
        waypointSet = true;
        mp.events.callRemote("SERVER:waypointToDriver", position.x, position.y);
    });

    mp.events.add("playerRemoveWaypoint", () => {
        waypointSet = false;
    });

    var timer;
    var val: number;
    var timeoutConter: number;

    mp.events.add("tpToWaypoint", () => {
        if (!waypointSet) {
            return;
        }
        val = 1000;
        timeoutConter = 0;

        let getGroundZ = mp.game.gameplay.getGroundZFor3dCoord(x_saved, y_saved, z_saved, 0, false);

        if (getGroundZ == 0) {
            mp.players.local.position = new mp.Vector3(x_saved, y_saved, val);
            mp.players.local.freezePosition(true);

            timer = setInterval(function () {
                getGroundZ = mp.game.gameplay.getGroundZFor3dCoord(x_saved, y_saved, val, 0, false);
                mp.players.local.freezePosition(false);
                mp.players.local.position = new mp.Vector3(x_saved, y_saved, val);

                if (getGroundZ == 0) {
                    timeoutConter++;
                    val -= 100;
                    mp.players.local.freezePosition(true);
                } else {
                    mp.players.local.position = new mp.Vector3(x_saved, y_saved, getGroundZ);
                    clearInterval(timer);
                }

                if (timeoutConter >= 20) {
                    mp.players.local.freezePosition(false);
                    clearInterval(timer);
                }
            }, 250);
        } else {
            mp.players.local.position = new mp.Vector3(x_saved, y_saved, getGroundZ);
        }
    });

}