(function () {
    global.dashModule.service('ordersUtilsService', ['$', '$http', '$translate', 'utilsService', ordersUtilsService]);

    function ordersUtilsService($, $http, $translate, utilsService) {
        let maxDeliveryDate = '';
        const earliestInstallationDate = {};
        const isNextStepTheOneWanted = {};
        const callbackMethods = {};

        return {
            hasExtraAction,
            calculatePrice,
            hasAgreement,
            setMaximumDeliveryDate,
            getEarliestInstallationDateFromDb,
            getEarliestInstallationDate,
            checkIfIsNextStepWanted,
            isComponentDisabled,
            registerOrderFunction,
            getOrderInfo
        };

        function hasExtraAction(step) {
            return step.stepType === 'extraAction' && step.status === 'in-progress';
        }

        function calculatePrice(values, units) {
            let total = 0;
            values.forEach((val) => {
                total += parseFloat(val);
            });

            return units ? total * units : 0;
        }

        function hasAgreement(packagePayPeriod, servicesContractPeriod) {
            return parseInt(packagePayPeriod) > 0 || parseInt(servicesContractPeriod) > 0;
        }

        function setMaximumDeliveryDate(idOrder, idPackage, earliestIntallationDate) {
            const params = $.param({
                idOrder,
                idPackage,
                maxDeliveryDate: earliestIntallationDate
            });

            if (!maxDeliveryDate) {
                maxDeliveryDate = '-';
            }

            if (earliestIntallationDate && earliestIntallationDate !== '-') {
                maxDeliveryDate = earliestIntallationDate;
                $http({
                    method: 'POST',
                    url: 'orders/api/setEarliestInstallationDateInDb',
                    data: params
                }).then(getMaximumDeliveryDate, utilsService.onHttpError);
            }
        }

        function getMaximumDeliveryDate(response) {
            if (typeof response.data !== 'undefined' && Object.keys(response.data).length) {
                getEarliestInstallationDateFromDb(response.data.idOrder, response.data.idPackage);
                displayMessage(response);

                if('callConfirmationInstallationDatesFct' in response.data && response.data.callConfirmationInstallationDatesFct) {
                    utilsService.executeRegisteredFunction('getConfirmationInstallationDates');
                }
            }
        }

        function getEarliestInstallationDateFromDb(idOrder, idPackage) {
            const params = $.param({
                idOrder,
                idPackage,
                maxDeliveryDate: maxDeliveryDate[idPackage]
            });

            $http({
                method: 'POST',
                url: 'orders/api/getEarliestInstallationDate',
                data: params
            }).then(setEarliestInstallationDate, utilsService.onHttpError);
        }

        function setEarliestInstallationDate(response) {
            if (typeof response.data !== 'undefined') {
                if (response.data.messages) {
                    displayMessage(response);
                }
                if (response.data.earliestInstallationDate) {
                    const paramData = {
                        idPackage: response.data.idPackage,
                        minDate: response.data.earliestInstallationDate
                    };
                    earliestInstallationDate[response.data.idOrder] = response.data.earliestInstallationDate;
                    utilsService.executeRegisteredFunction('setMinDateAvailable', paramData);
                }
            }
        }

        function getEarliestInstallationDate(idOrder) {
            return earliestInstallationDate[idOrder] || '-';
        }

        function checkIfIsNextStepWanted(idOrder, usedForDirective, stepIds) {
            const params = $.param({
                idOrder,
                stepIds: JSON.stringify(stepIds)
            });

            $http({
                method: 'POST',
                url: 'orders/api/checkIfIsNextStepWanted',
                data: params
            }).then((response) => {
                isNextStepWanted(response, idOrder, usedForDirective);
            }, utilsService.onHttpError);
        }

        function isNextStepWanted(response, idOrder, usedForDirective) {
            if(typeof response.data !== 'undefined') {
                if(!isNextStepTheOneWanted[usedForDirective]) {
                    isNextStepTheOneWanted[usedForDirective] = {};
                }
                isNextStepTheOneWanted[usedForDirective][idOrder] = response.data;
            }
        }

        function isComponentDisabled(idOrder, usedForDirective) {
            if(isNextStepTheOneWanted[usedForDirective] && isNextStepTheOneWanted[usedForDirective][idOrder]) {
                return isNextStepTheOneWanted[usedForDirective][idOrder];
            }
            return false;
        }

        function registerOrderFunction(key, showOrderInfo) {
            callbackMethods[key] = showOrderInfo;
        }

        function getOrderInfo() {
            const idOrder = global.getParameterByName('idOrder') || 0;
            const params = $.param({
                idOrder
            });

            $http({
                method: 'POST',
                url: 'orders/api/getOrderInfo',
                data: params
            }).then(callbackMethods.showOrderInfo, utilsService.onHttpError);
        }

        function displayMessage(response) {
            if (typeof response.data.messages !== 'undefined') {
                response.data.messages.forEach((messageObj) => {
                    let translatedMessage = $translate.instant('orders.messages.' + messageObj.message);
                    const messageKey = 'key' in messageObj ? ' ' + messageObj.key : '';
                    utilsService.displayMessage(messageObj.code, translatedMessage + messageKey);
                });
            }
        }
    }
})();
