import Vue from 'vue';
//import { getAuthUser } from './auth';

/* eslint-disable */

const loginUrl = process.env.VUE_APP_LOGIN_URL ? process.env.VUE_APP_LOGIN_URL : '/gate/sign-in';
const homeUrl = process.env.VUE_APP_ME_URL ? process.env.VUE_APP_ME_URL + '/b2b' : '/';
const vueMaintenanceMode = process.env.VUE_APP_MAINTENANCE_MODE;

const loginInterrupt = function(current_url, message) {

    if(!current_url.includes("gate/sign-in"))
    sessionStorage.crinterrupted_page = current_url;
    sessionStorage.crinterrupt_message = message;

    if(!current_url.includes("gate/sign-in"))
    window.location.href = loginUrl;
}

const redirectToInterruptedPage = function() {
    //sessionStorage.crinterrupted_page.clear();
    const url = sessionStorage.crinterrupted_page;
    if (url) {
        window.location.href = url;
        sessionStorage.removeItem("crinterrupted_page");
    }
    //window.location.href = homeUrl;
    else
        window.location.href = homeUrl;
}

const beforeEachRoute = (to, from, next) =>{    
  
    if (!to.matched.length) {
        location.href = to.path;
    }
    if (vueMaintenanceMode == "true" && to.name !== "Maintenance") {
        next({
            name: "Maintenance" // back to safety route //
        })
    }
    try {
        let path = to.path;
       // console.log("to path", to);
        if (path.includes("shop/category")) {
            let routeSplit = path.split("/");
            let newCategoryRoute = routeSplit.slice(3, routeSplit.length - 5).join("/");
           // console.log("new route", newCategoryRoute);
            next({ path: "/" + newCategoryRoute });
        }
    } catch (error) {
        next({ path: "/" });
    }
    next();
}
const meWrapRequest = fn => (...params) =>
    fn(...params)
    .then(response => {
        if (!response.ok) {
            throw response;
        }
        return response.json();
    })
    .catch(error => meHandleError(error));

const meHandleError = async errorResponse => {
    if (!errorResponse.ok) {
        switch (errorResponse.status) {
            case 401:
                {
                    if (localStorage.getItem("cr_changePassowrd") == "true") {
                        localStorage.clear("cr_changePassowrd")
                    } else {
                        loginInterrupt(window.location.href, 'There was an access violation caused by your request. You need to sign back in please.');
                    }
                    break;
                }
            case 400:
                {
                    const text_400 = await errorResponse.text();
                    const data_400 = JSON.parse(text_400);
                    throw data_400;
                }
            case 500:
                {
                    const text_500 = await errorResponse.text();
                    const data_500 = JSON.parse(text_500);
                    throw data_500;
                }

            default:
                const error_text = await errorResponse.text();
                const error_data = JSON.parse(error_text);
                throw error_data;

        } //switch
    }
};

const wrapRequest = fn => (...params) =>
    fn(...params)
    .then(response => {
        if (!response.ok) {
            throw response;
        }
        return response.json();
    })
    .catch(error => handleError(error));

const handleError = async errorResponse => {
    if (!errorResponse.ok) {
        switch (errorResponse.status) {
            case 403:
                {
                    const text_403 = await errorResponse.text();
                    //console.log('error:', text_403);
                    const data_403 = JSON.parse(text_403);
                    if (typeof Vue.$snotify != 'undefined') {
                        Vue.$snotify.error(data_403.message);
                    }
                    throw data_403;
                    //break;
                }

            case 401:
                {
                    const text_401 = await errorResponse.text();
                    //console.log('error:', text_403);
                    const data_401 = JSON.parse(text_401);
                    if (typeof Vue.$snotify != 'undefined') {
                        Vue.$snotify.error(data_401.message);
                    }
                    // throw data_401;

                    loginInterrupt(window.location.href, 'There was an access violation caused by your request. You need to sign back in please.');
                    break;
                }
            case 400:
                {
                    const text_400 = await errorResponse.text();
                    const data_400 = JSON.parse(text_400);
                    if (data_400.code == "22023" && data_400.message.indexOf('role') >= 0 &&
                        data_400.message.indexOf('does not exist')) {
                        loginInterrupt(window.location.href, 'There was an access violation caused by your request. You need to sign back in please.');
                    } else {
                        if (typeof Vue.$snotify != 'undefined') {
                            Vue.$snotify.error('Unexpected error while communicating with the cloud');
                        }
                        throw data_400;
                    }
                    break;
                }
            case 404:
                {
                    const text_404 = await errorResponse.text();
                    const data_404 = JSON.parse(text_404);
                    throw data_404;
                    break;
                }
            case 500:
                {
                    const text_500 = await errorResponse.text();
                    const data_500 = JSON.parse(text_500);
                    if (data_500.code == "22023" && data_500.message.indexOf('role') >= 0 &&
                        data_500.message.indexOf('does not exist')) {
                        loginInterrupt(window.location.href, 'There was an access violation caused by your request. You need to sign back in please.');
                    } else {
                        if (typeof Vue.$snotify != 'undefined') {
                            Vue.$snotify.error('Unexpected error while communicating with the cloud');
                        }
                        throw data_500;
                    }
                    break;
                }
            default:
                if (typeof Vue.$snotify != 'undefined') {
                    Vue.$snotify.error('Unexpected error while communicating with the cloud');
                }
                throw { message: 'Unexpected error while communicating with the cloud' };

        } //switch
    }
};
export {
    loginInterrupt,
    redirectToInterruptedPage,
    beforeEachRoute,
    wrapRequest,
    handleError,
    meWrapRequest
};