import {API_SERVER} from '../../config';
import HtmlClient from '../../helpers/HtmlClient';
import {
    REQUEST_SHOP_CART_COUNT,
    RECEIVE_SHOP_CART_COUNT,
    REQUEST_SHOP_CART_ITEMS,
    RECEIVE_SHOP_CART_ITEMS,
    SET_CURRENT_STEP,
    RESET_STEPS,
    GO_TO_NEXT_STEP,
    GO_TO_PREVIOUS_STEP,
    LOAD_CART_STEPS,
    cartSteps,
    UPLOAD_DOCUMENT,
    REQUEST_CART_DOCUMENTS,
    RECEIVE_CART_DOCUMENTS,
    REQUEST_CUSTOMER_DETAILS,
    RECEIVE_CUSTOMER_DETAILS,
    SELECT_COUNTRY_DELIVERY,
    SELECT_COUNTRY_BILLING,
    SET_ORDER_INFO,
    IS_CART_ITEMS_DISABLED,
    RECEIVE_ORDER_TOTAL_PRICE,
    UPDATE_CART_ITEMS,
    SET_NEXT_STEP,
    SET_PREV_STEP,
    SET_ORDER_PLACED,
    SET_ORDER_PLACED_REDIRECT,
    cartMessages
} from '../../constants/cartConstants';
import {updateMessages} from '../notification/notificationActions';
import { fromWCCartItems } from '../../helpers/CartHelper';

const client = new HtmlClient();

export const requestShopCartCount = () => ({type: REQUEST_SHOP_CART_COUNT});
export const receiveShopCartCount = (json) => ({type: RECEIVE_SHOP_CART_COUNT, cartCount: json});

export const requestShopCartItems = () => ({
    type: REQUEST_SHOP_CART_ITEMS,
    isLoading: true
});
export const receiveShopCartItems = (json) => ({
    type: RECEIVE_SHOP_CART_ITEMS,
    isLoading: false,
    cartItems: json
});

export const requestCustomerDetails = () => ({
    type: REQUEST_CUSTOMER_DETAILS,
    isLoading: true
});
export const receiveCustomerDetails = (json) => ({
    type: RECEIVE_CUSTOMER_DETAILS,
    isLoading: false,
    customerDetails: json
});

export const fetchCartCount = () => {
    return dispatch => {
        dispatch(requestShopCartCount());

        return client.fetch({url: `${API_SERVER}/wp-json/wiaas/cart/count`}).then(response => {
            if (typeof response.data !== 'undefined' && 'count' in response.data) {
                dispatch(receiveShopCartCount(response.data.count));
            }
        }).catch(error => {
            client.onError(error, dispatch);
        });
    }
}

export const fetchCartNotices = () => {

};

export const fetchCartItems = (isForSteps = false) => {
    return dispatch => {
        dispatch(requestShopCartItems());
        return client.fetch({url: `${API_SERVER}/wp-json/wiaas/cart/items`}).then(response => {
            if (typeof response.data !== 'undefined' && 'items' in response.data) {

                const cartItems = response.data.items.map(wcCartItem => fromWCCartItems(wcCartItem));

                dispatch(receiveShopCartItems(cartItems));
                dispatch(fetchCartDocuments(cartItems.map((cartItem) => cartItem.idPackage), isForSteps));
                dispatch(updateOrderTotalPrice(cartItems));
            }
        }).catch(error => {
            client.onError(error, dispatch);
        });
    }
}

const updateOrderTotalPrice = (cartItems) => ({type: RECEIVE_ORDER_TOTAL_PRICE, cartItems});

const updateCartItems = (newItem)=>(
    {type: UPDATE_CART_ITEMS, newItem}
);

export const updateQuantity = (cartItem, quantity, updateCartAllItems) => {

    return dispatch => {
        return client.fetch({
            url: `${API_SERVER}/wp-json/wiaas/cart/items/${cartItem.key}`,
            method: 'post',
            data: {
                quantity
            }
        }).then(response => {
            if (typeof response.data !== 'undefined' && 'messages' in response.data) {
                const filteredMessages = response.data.messages.filter(message => {
                    return message.code === 'error';
                });

                if(filteredMessages.length > 0){
                    dispatch(updateMessages(filteredMessages, cartMessages));
                }else{
                    cartItem.quantity = quantity;
                    dispatch(updateCartItems(cartItem));
                }
            }
        }).catch(error => {
            client.onError(error, dispatch);
        });
    }
}

export const removeCartItem = (cartItemKey) => {
    return dispatch => {
        return client.fetch({
            url: `${API_SERVER}/wp-json/wiaas/cart/items/${cartItemKey}`,
            method: 'delete',
        }).then(response => {
            if (typeof response.data !== 'undefined' && 'messages' in response.data) {
                dispatch(updateMessages(response.data.messages, cartMessages));
                response.data.messages.forEach(messageObject => {
                    if (messageObject.code === 'success') {
                        dispatch(fetchCartCount());
                        dispatch(fetchCartItems(true));
                    }
                })
            }
        }).catch(error => {
            client.onError(error, dispatch);
        });
    }
}

const getSteps = (whitoutUploadDoc) => {
    const newSteps = Object.assign({}, cartSteps());

    if(whitoutUploadDoc) {
        delete newSteps.cartUploadDocuments;
        newSteps.cartCustomerDetails.previous = null;
        newSteps.cartCustomerDetails.status = 'active';
    }

    return {
        type: LOAD_CART_STEPS,
        cartSteps: newSteps
    };
};

export const loadSteps = (whitoutUploadDoc) => {
    const firstStep = whitoutUploadDoc ? 'cartCustomerDetails' : 'cartUploadDocuments';

    return dispatch => {
        dispatch(getSteps(whitoutUploadDoc));
        dispatch(selectStep(firstStep));
        dispatch(resetSteps());
        dispatch(setCartItemsDisabled(false));
    }
}

export const selectStep = (step, params={}) => {
    return {type: SET_CURRENT_STEP, currentStep: step, params};
}

const resetSteps = () => ({type: RESET_STEPS});

export const getCustomerDetails = () => {
    return dispatch => {
        dispatch(receiveCustomerDetails({
            "companyName": "Coor Service Management AB",
            "vatCode": "556084-6783",
            "details": {
                "idBillingAddress": null,
                "idDeliveryAddress": null,
                "idProject": null,
                "reference": null,
                "tender": null
            },
            "billing": [
                {
                    "id": 1,
                    "city": "Göteborg",
                    "countryName": "SE",
                    "detailedAddress": "Lilla Bommen 2",
                    "firstName": "Customer",
                    "lastName": "User",
                    "zipCode": "12323"
                }
            ],
            "deliveryAddresses": [
                {
                    "id": 1,
                    "city": "Göteborg",
                    "countryName": "Göteborg",
                    "detailedAddress": "Lilla Bommen 2",
                    "zipCode": "12323"
                }
            ]
        }));
        // return client.fetch({url: `${API_SERVER}/wp-json/wiaas/cart/customer-details`})
        // .then(response => {
        //     if (typeof response.data !== 'undefined' && response.data.customerDetails) {
        //         const customerDetails = response.data.customerDetails;
        //         dispatch(receiveCustomerDetails(customerDetails));
        //     }
        // }).catch(error => {
        //     client.onError(error, dispatch);
        // });
    }
}

export const nextStep = (step) => ({type: GO_TO_NEXT_STEP});
export const previousStep = (params) => ({type: GO_TO_PREVIOUS_STEP, params});

export const uploadDocumnet = () => ({type: UPLOAD_DOCUMENT});

export const uploadOrderDocument = (packageCartKey, idDocumentType, file, packages) => {
    return dispatch => {
        dispatch(uploadDocumnet());

        return client.uploadFile(file, {
            url: `${API_SERVER}/wp-json/wiaas/cart/documents`,
            data: {
                'doc_type': idDocumentType,
                'package_key': packageCartKey
            }
        }).then(response => {
            if (typeof response.data !== 'undefined' && 'messages' in response.data) {
                dispatch(updateMessages(response.data.messages, cartMessages));
                dispatch(fetchCartDocuments(packages));
            }
        }).catch(error => {
            client.onError(error, dispatch);
        });
    }
}

export const badFile = () =>{
    return dispatch => {
        dispatch(updateMessages([{code: 'warning', message: 'INVALID_FILE'}], cartMessages));
    }
}

export const requestCartDocuments = () => ({
    type: REQUEST_CART_DOCUMENTS,
    isLoading: true
});
export const receiveCartDocuments = (json) => ({
    type: RECEIVE_CART_DOCUMENTS,
    isLoading: false,
    cartDocuments: json
});

export const fetchCartDocuments = (packages, isForSteps = false) => {
    return dispatch => {
        dispatch(requestCartDocuments());

        return client.fetch({
            url: `${API_SERVER}/wp-json/wiaas/cart/documents`,
            method: 'get',
            data: {packages}
        }).then(response => {
            if (response.data) {
                dispatch(receiveCartDocuments(response.data));
                if(isForSteps) {
                    const whitoutUploadDoc = response.data.templates.length === 0;
                    dispatch(loadSteps(whitoutUploadDoc));
                }
            }
        }).catch(error => {
            client.onError(error, dispatch);
        });
    }
}

export const selectCountryDelivery = (country) => ({type: SELECT_COUNTRY_DELIVERY, selectedCountryDelivery: country});
export const selectCountryBilling = (country) => ({type: SELECT_COUNTRY_BILLING, selectedCountryBilling: country});

export const saveOrderDetails = (orderDetails, cartItems) => {
    const orderInfo = {orderDetails, cartItems};
    return dispatch => {
        dispatch(getCustomerDetails());
        dispatch(setOrderInfo(orderInfo));
        // return client.fetch({
        //     url: `${API_SERVER}/cart/api/saveOrderDetails`,
        //     method: 'post',
        //     data: {orderDetails, cartItems}
        // }).then(response => {
        //     if (typeof response.data !== 'undefined' && 'messages' in response.data) {
        //         dispatch(getCustomerDetails());
        //         dispatch(setOrderInfo(orderInfo));
        //     }
        // }).catch(error => {
        //     client.onError(error, dispatch);
        // });
    }
}

export const setOrderInfo = (info) => ({type: SET_ORDER_INFO, orderInfo: info});

export const setOrderPlacedFlag = (flag) => ({type: SET_ORDER_PLACED, orderPlaced: flag});
export const setOrderPlacedRedirectFlag = (flag) => ({type: SET_ORDER_PLACED_REDIRECT, orderPlacedRedirect: flag});

export const placeOrder = (orderInfo) => {
    const {orderDetails, cartItems} = orderInfo;
    return dispatch => {
        return client.fetch({
            url: `${API_SERVER}/wp-json/wiaas/cart/checkout`,
            method: 'post',
            data: {
                vat: orderDetails.vatCode,
                company: orderDetails.companyName,
                reference: orderDetails.details.reference,
                tender: orderDetails.details.tender,
                project_id: orderDetails.details.idProject,
                delivery_address_id: orderDetails.delivery.id,
                billing_address_id: orderDetails.billing.id,
                shipping_city: orderDetails.delivery.city,
                shipping_country: orderDetails.delivery.countryName,
                shipping_address_1: orderDetails.delivery.detailedAddress,
                shipping_postcode: orderDetails.delivery.zipCode,
                shipping_first_name: orderDetails.delivery.firstName,
                shipping_last_name: orderDetails.delivery.lastName,
                billing_city: orderDetails.billing.city,
                billing_country: orderDetails.billing.countryName,
                billing_address_1: orderDetails.billing.detailedAddress,
                billing_postcode: orderDetails.billing.zipCode,
                billing_first_name: orderDetails.billing.firstName,
                billing_last_name: orderDetails.billing.lastName,
                billing_last_email: orderDetails.billing.invoiceMail
            }
        }).then(response => {
            if (typeof response.data !== 'undefined' && 'messages' in response.data) {
                dispatch(updateMessages(response.data.messages, cartMessages));
                if(!checkIfErrorMessageExists(response.data.messages)) {
                    dispatch(fetchCartCount());
                    dispatch(setOrderPlacedFlag(true));
                    dispatch(setOrderPlacedRedirectFlag(true));
                }
            }
        }).catch(error => {
            client.onError(error, dispatch);
        });
    }
}

const checkIfErrorMessageExists = (messagesArray) => {
    return messagesArray.some(messageObj => {
        return messageObj.code === 'error';
    });
}

export const setCartItemsDisabled = (flag) => ({type: IS_CART_ITEMS_DISABLED, isCartItemsDisabled: flag});

export const setNextActionFct = (fct) => ({type: SET_NEXT_STEP, nextStepAction: fct});
export const setPrevActionFct = (fct) => ({type: SET_PREV_STEP, prevStepAction: fct});
