import * as NativeUI from 'NativeUI';

export default function (globalData: GlobalData) {

    mp.events.add("SERVER:Job_ShowJobMenu", (jobName: string, data: any) => {
        if (globalData.InMenu) return;

        var menu = new NativeUI.Menu("Job", jobName, new NativeUI.Point(50, 50), null, null);
        menu.AddItem(new NativeUI.UIMenuItem("Job starten"));
        menu.AddItem(new NativeUI.UIMenuItem("Job beenden"));

        globalData.InMenu = true;

        data = JSON.parse(data);

        if (data) {
            if (data.Id === 1) { // Taxi Driver
                var status = data.Status;
                if (data.JobData.TaxiCalls && status === 0) { // Spieler hat keinen aktiven Auftrag
                    var calls = data.JobData.TaxiCalls;
                    var taxiCallsItem = new NativeUI.UIMenuItem("Taxi Aufträge");
                    var taxiCallsCount = calls.length;
                    taxiCallsItem.SetRightLabel(taxiCallsCount.toString());
                    menu.AddItem(taxiCallsItem);

                    if (taxiCallsCount > 0) {
                        var taxiCallsMenu = new NativeUI.Menu("Taxi-Aufträge", "Wähle einen Auftrag aus", new NativeUI.Point(50, 50), null, null);
                        calls.forEach(call => {
                            var item = new NativeUI.UIMenuItem(call.Name);
                            item.SetRightLabel(call.Distance.toString() + "m");
                            taxiCallsMenu.AddItem(item);
                        });
                        taxiCallsMenu.Visible = false;
                        menu.BindMenuToItem(taxiCallsMenu, taxiCallsItem);

                        taxiCallsMenu.ItemSelect.on((item: NativeUI.UIMenuItem, index: number) => {
                            mp.events.callRemote("CLIENT:JobManager_TaxiJob_AcceptCall", item.Text);
                            menu.Close();
                        });
                    }
                } else if (status === 1) { // Spieler hat aktiven Auftrag
                    var cancelTaxiContractItem = new NativeUI.UIMenuItem("Taxi-Auftrag abbrechen");
                    cancelTaxiContractItem.SetRightLabel(data.JobData.Name);
                    menu.AddItem(cancelTaxiContractItem);
                }
            }
        }

        menu.ItemSelect.on((item: NativeUI.UIMenuItem, index: number) => {
            if (index === 0) { // Job starten
                mp.events.callRemote("CLIENT:Job_StartJob");
            } else if (index === 1) { // Job stoppen
                mp.events.callRemote("CLIENT:Job_StopJob");
            } else {
                return;
            }
            menu.Close();
        });

        menu.MenuClose.on(() => {
            globalData.InMenu = false;
        })
    });

}