import $j from './lib/jquery';
import FreyaSyncService from './freya-sync-service';

export default class OrderResync {
    private static instance: OrderResync;
    private orderId: number | undefined = undefined;
    private locationUid?: string;
    private needsResync = false;

    private constructor() {
        this.setupJquery();
    }

    public static bootstrap(): void {
        if (this.instance) {
            return;
        }

        this.instance = new OrderResync();
    }

    public static get sharedInstance(): OrderResync {
        if (!this.instance) {
            throw new Error('No OrderResync instance');
        }

        return this.instance;
    }

    public getOrder() {
        if (!this.orderId) {
            return;
        }
        const resyncButton = $j('#fsResyncOrder');

        resyncButton.prop('disabled', true);

        $j.ajax({
            url: FreyaSyncService.sharedInstance.data.ajax_url,
            dataType: 'json',
            type: 'GET',
            data: {
                action: 'fss_get_order_location',
                id: this.orderId,
                nonce: FreyaSyncService.sharedInstance.data.nonce,
            },
            success: (res: { data: { locationUid: string; needsResync: boolean } }) => {
                this.locationUid = res.data.locationUid;
                this.needsResync = res.data.needsResync;
                if (this.needsResync) {
                    resyncButton.prop('disabled', false);
                    resyncButton.on('click', () => {
                        this.resyncOrder();
                    });
                }
            },
            error: (jqXHR: JQuery.jqXHR) => {
                console.log(jqXHR);
            },
        });
    }

    private resyncOrder(): void {
        if (!this.needsResync) {
            return;
        }

        if (!this.locationUid || this.locationUid === '') {
            this.locationUid = FreyaSyncService.sharedInstance.settings.fsDefaultLocationUid;
        }

        const resyncButton = $j('#fsResyncOrder');
        const resyncMessage = $j('#fsResyncMessage');

        resyncButton.prop('disabled', true);
        resyncMessage.text('').addClass('hidden').removeClass('fss-notice-success').removeClass('fss-notice-error');

        $j.ajax({
            url: FreyaSyncService.sharedInstance.data.ajax_url,
            dataType: 'json',
            type: 'POST',
            data: {
                action: 'fss_resync_order',
                order_id: this.orderId,
                location_uid: this.locationUid,
                nonce: FreyaSyncService.sharedInstance.data.nonce,
            },
            success: () => {
                resyncButton.prop('disabled', false);
                resyncMessage
                    .addClass('fss-notice-success')
                    .removeClass('hidden')
                    .text('Comanda se va resincroniza în curând...');
            },
            error: (jqXHR: JQuery.jqXHR) => {
                let message = 'Nu am putut sincroniza comanda din cauza unei erori interne!';
                if (jqXHR.status === 404) {
                    message = 'Locația asociată comenzii nu mai există în sistemul Freya Sync sau este invalidă.';
                }
                resyncButton.prop('disabled', false);
                resyncMessage.text(message).addClass('fss-notice-error').removeClass('hidden');
            },
        });
    }

    private setupJquery() {
        const id = $j('#FS_ORDER_ID').attr('data-id');
        if (!id) {
            return;
        }
        this.orderId = Number(id);
        this.getOrder();
    }
}
