import { authHeader } from './auth';
import { wrapRequest, meWrapRequest } from './nav';

const vueAppMagenotApiUrl = process.env.VUE_APP_MAGENTO_API_URL;
//const vueAppCCUrl = process.env.VUE_APP_CC_URL;
const retailorId = process.env.VUE_APP_RETAILOR_ID;
const vueAppNodeslsApiUrl = process.env.VUE_APP_NODESLS_API_URL;
const assetNodeslsUrl = process.env.VUE_APP_ASSETS_NODESLS_URL;

// export const doValidateAddress = wrapRequest((address) => {
//     const requestOptions = {
//         method: 'GET',
//     };
//     return fetch("https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=AIzaSyDmHp0PPuKHD1KGHCDmLq1qQKr_03XKEHo", requestOptions);
// });
/*eslint-disable*/
export const doValidateAddress = wrapRequest((address) => {
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
            ...authHeader()
        },
        body: JSON.stringify({
            "address": {
                "countryId": address.countryId,
                "regionId": address.regionId,
                "region": address.region ? address.region.region : "",
                "street": [address.streetNoOne, address.streetNoTwo],
                "company": address.company ? address.company : "",
                "telephone": address.telephone,
                "postcode": address.postcode,
                "city": address.city,
                "firstname": address.firstname,
                "lastname": address.lastname,
            }
        })
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/carts/mine/validate-address`, requestOptions);
});
export const doValidateAddressCheckout = wrapRequest((address, stateName) => {
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-type': 'application/json'
        },
        body: JSON.stringify({
            "address": {
                "countryId": address.countryId,
                "regionId": address.regionId,
                "region": stateName,
                "street": [address.streetNoOne, address.streetNoTwo],
                "telephone": address.telephone,
                "postcode": address.postcode,
                "city": address.city,
                "firstname": address.firstname,
                "lastname": address.lastname,
            }
        })
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/shipping-information/validate-address`, requestOptions);
});
export const doFetchStates = wrapRequest(() => {
    const requestOptions = {
        method: 'GET',
        headers: {
            'Content-type': 'application/json'
        }
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/directory/countries/US`, requestOptions)

});
export const doFetchCountries = wrapRequest(() => {
    const requestOptions = {
        method: 'GET',
        headers: {
            'Content-type': 'application/json'
        }
    };

    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/directory/countries`, requestOptions)

});
export const doFetchBasicInfo = meWrapRequest(() => {
    const requestOptions = {
        method: 'GET',
        headers: {
            'Content-type': 'application/json',
            ...authHeader()
        },
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/customers/me`, requestOptions)
});
/*
export const doFetchChangePassword = wrapRequest((token) => {
    const requestOptions = {
        method: 'PUT',
        headers: { 'Content-type': 'application/json'
    , 'Authorization' : `Bearer ${token}`}
    };
    
    return fetch(`https://magento2.test/rest/crn_retailer/V1/customers/retailer/password`, requestOptions)

});*/
export const doFetchChangePassword = async (currentPassword, newPassword) => {

    /* eslint-disable no-alert, no-console ,   */
    console.log("currentPassword: ", currentPassword)
    console.log("newPassword : ", newPassword)

    return false;
};
export const doUpdateAddress = meWrapRequest((one, address) => {
    const requestOptions = {
        method: 'PUT',
        headers: {
            'Content-type': 'application/json',
            ...authHeader()
        },
        body: JSON.stringify({
            "customer": {
                "firstname": one.firstname,
                "lastname": one.lastname,
                "email": one.email,
                "website_id": one.websiteId,
                "addresses": [{
                    "region_id": address.regionId,
                    "country_id": address.countryId,
                    "street": [
                        address.streetNoOne, address.streetNoTwo
                    ],
                    "postcode": address.postcode,
                    "city": address.city,
                    "telephone": address.telephone,
                    "firstname": address.firstname,
                    "lastname": address.lastname
                }],
                "default_shipping": one.defaultShipping,
                "default_billing": one.defaultBilling
            }
        })
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/customers/me`, requestOptions)
});
export const doUpdateUserAddress = meWrapRequest((one, addresses) => {
    const requestOptions = {
        method: 'PUT',
        headers: {
            'Content-type': 'application/json',
            ...authHeader()
        },
        body: JSON.stringify({
            "customer": {
                "firstname": one.firstname,
                "lastname": one.lastname,
                "email": one.email,
                "website_id": one.websiteId,
                "addresses": addresses,
                "default_shipping": one.defaultShipping,
                "default_billing": one.defaultBilling
            }
        })
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/customers/me`, requestOptions)
});
export const doUpdateSubscription = meWrapRequest((one) => {

    const requestOptions = {
        method: 'PUT',
        headers: {
            'Content-type': 'application/json',
            ...authHeader()
        },
        body: JSON.stringify({
            "customer": {
                "firstname": one.firstname,
                "lastname": one.lastname,
                "email": one.email,
                "website_id": one.websiteId,
                "extension_attributes": {
                    "is_subscribed": one.extensionAttributes.isSubscribed
                }
            }
        })
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/customers/retailer`, requestOptions)
});
export const doChangeBasicInfo = meWrapRequest((one) => {
    const requestOptions = {
        method: 'PUT',
        headers: {
            'Content-type': 'application/json',
            ...authHeader()
        },
        body: JSON.stringify({
            "customer": {
                "firstname": one.firstname,
                "lastname": one.lastname,
                "email": one.email,
                "website_id": one.websiteId
            }
        })
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/customers/me`, requestOptions)
});
export const doChangePassword = meWrapRequest((currentPassword, newPassword) => {
    const requestOptions = {
        method: 'PUT',
        headers: {
            'Content-type': 'application/json',
            ...authHeader()
        },
        body: JSON.stringify({
            "currentPassword": currentPassword,
            "newPassword": newPassword
        })
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/customers/me/password`, requestOptions)
});
export const doFetchEstimatedShippingMethods = wrapRequest((one, address) => {
    let streetAddress = [];
    let streetArray = [];
    if (address.streetNoTwo == " " || address.streetNoTwo == undefined) {
        streetAddress[0] = address.streetNoOne;
        streetArray = streetAddress.filter(v => v != '');
    } else {
        streetAddress[0] = address.streetNoOne
        streetAddress[1] = address.streetNoTwo;
        streetArray = streetAddress.filter(v => v != '');
    }
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
            ...authHeader()
        },
        body: JSON.stringify({
            /*"address": {
                 "region_id": regionId,
                 "country_id": countryId
             }*/
            "address": {
                "region": address.region.region,
                "region_id": address.regionId,
                "region_code": address.regionCode,
                "country_id": address.countryId,
                "street": streetArray,
                "postcode": address.postcode,
                "city": address.city,
                "firstname": address.firstname,
                "lastname": address.lastname,
                "customer_id": one.id,
                "email": one.email,
                "telephone": address.telephone,
                "same_as_billing": 1
            }
        }),

    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/carts/mine/estimate-shipping-methods`, requestOptions)
});
export const doShippingInformation = wrapRequest((one, address, estimated, suggestedAddress) => {
    let streetAddress = [];
    let streetArray = [];
    if (address.streetNoTwo == " " || address.streetNoTwo == undefined) {
        streetAddress[0] = suggestedAddress.streetNoOne ? suggestedAddress.streetNoOne : address.streetNoOne;
        streetArray = streetAddress.filter(v => v != '');
    } else {
        streetAddress[0] = suggestedAddress.streetNoOne ? suggestedAddress.streetNoOne : address.streetNoOne
        streetAddress[1] = suggestedAddress.streetNoTwo ? suggestedAddress.streetNoTwo : address.streetNoTwo;
        streetArray = streetAddress.filter(v => v != '');
    }
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
            ...authHeader()
        },
        body: JSON.stringify({
            "addressInformation": {
                "shipping_address": {
                    "region_id": suggestedAddress.region_id ? suggestedAddress.region_id : address.regionId,
                    "country_id": suggestedAddress.country_id ? suggestedAddress.country_id : address.countryId,
                    "street": streetArray,
                    "postcode": suggestedAddress.postcode ? suggestedAddress.postcode : address.postcode,
                    "city": suggestedAddress.city ? suggestedAddress.city : address.city,
                    "firstname": address.firstname,
                    "lastname": address.lastname,
                    "customer_id": one.id,
                    "email": one.email,
                    "telephone": address.telephone
                },
                "shipping_carrier_code": estimated.carrierCode,
                "shipping_method_code": estimated.methodCode
            }
        })
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/carts/mine/shipping-information`, requestOptions)
});
export const doDeleteAddress = wrapRequest((addressId) => {
    const requestOptions = {
        method: 'DELETE',
        headers: {
            'Content-type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            ...authHeader()
        }
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/addresses/${addressId}`, requestOptions)
});

export const doProductsOrder = meWrapRequest((userQuote, paymentMethod, oneAddress) => {
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
            ...authHeader()
        },
        body: JSON.stringify({
            "cartId": userQuote,
            "billingAddress": oneAddress,
            "paymentMethod": paymentMethod,
            "comments": "",
        })
    };
    return fetch(`${vueAppMagenotApiUrl}/rest/crn_retailer/V1/carts/mine/payment-information`, requestOptions)
});

/*export const doProductsOrderOnCC = meWrapRequest((orderNumber, shippingAddress, webOrderNumber) => {
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-Type':'text/xml',
        },
    };
    let address2 = shippingAddress.street[1]? '&ShipToAddress2='+shippingAddress.street[1] : '';
    return fetch(`${vueAppCCUrl}?Operation=SUBMIT&RetailerID=${retailorId}&OrderNumber=${orderNumber}&ShipToFirstName=${shippingAddress.firstname}&ShipToLastName=${shippingAddress.lastname}&ShipToAddress1=${shippingAddress.street[0]}${address2}&ShipToCity=${shippingAddress.city}&ShipToState=${shippingAddress.regionCode}&ShipToZip=${shippingAddress.postcode}&ShipToCountry=${shippingAddress.countryId}&ShipToPhone=${shippingAddress.telephone}&ShipToEmail=${shippingAddress.email}&ShippingMethod=usp&WebOrderNumber=${webOrderNumber}`, requestOptions)
});*/
export const doProductsOrderOnCC = meWrapRequest((orderNumber, shippingAddress, webOrderNumber, estimatedShipping) => {
    let address2 = shippingAddress.street[1] ? escape(shippingAddress.street[1]) : undefined;
    let method = 'bes';
    if (estimatedShipping) {
        method = estimatedShipping.methodCode.substring(0, 3);
    }
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-type': 'application/json'
        },
        body: JSON.stringify({
            "retailorId": retailorId,
            "orderNumber": orderNumber,
            "shipToFirstName": escape(shippingAddress.firstname),
            "shipToLastName": escape(shippingAddress.lastname),
            "shipToAddress1": escape(shippingAddress.street[0]),
            "shipToAddress2": address2,
            "shipToCity": shippingAddress.city,
            "shipToState": shippingAddress.regionCode,
            "shipToZip": shippingAddress.postcode,
            "shipToCountry": shippingAddress.countryId,
            "shipToPhone": shippingAddress.telephone,
            "shipToEmail": shippingAddress.email,
            "shippingMethod": method,
            "webOrderNumber": webOrderNumber
        })
    };

    return fetch(`${vueAppNodeslsApiUrl}/cc-submit-order`, requestOptions)
});
/*  personalise order
export const doProductsOrderOnPersonalize = meWrapRequest((order) => {
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
        },
        body: JSON.stringify({
            "order": order
        })
    };
    return fetch(`http://order.crane.com/Incoming/input`, requestOptions)
});*/


export const doFetchProductPdfs = meWrapRequest((orderNumber, itemId) => {
    const requestOptions = {
        method: 'GET'
    };
    return fetch(`${assetNodeslsUrl}/order-builder-2?orderId=${orderNumber}&itemId=${itemId}`, requestOptions)
});