(function () {
    global.dashModule
        .controller('assignBrokerCtrl', ['$scope', '$http', '$', '$translate', 'utilsService', assignBrokerCtrl])
        .directive('assignBroker', [assignBrokerDirective]);

    function assignBrokerDirective() {
        return {
            restrict: 'E',
            templateUrl: 'orders/html/assignBrokerTemplate'
        };
    }

    function assignBrokerCtrl($scope, $http, $, $translate, utilsService) {
        $scope.assignBroker = assignToBroker;
        $scope.removeAssign = removeAssign;
        $scope.selectedBroker = '';

        function getIdBroker(brokerName) {
            const foundBroker = $scope.brokers.find(broker => {
                return broker.brokerName === brokerName;
            });

            return foundBroker && foundBroker.idBroker ? foundBroker.idBroker : 0;
        }

        function assignToBroker() {
            const idBroker = getIdBroker($scope.selectedBroker);

            if (idBroker === 0) {
                const translatedMessage = $translate.instant('orders.messages.INVALID_BROKER');
                utilsService.displayMessage('error', translatedMessage);
                $scope.selectedBroker = '';
            } else {
                const params = $.param({
                    idOrder: $scope.idOrder,
                    idBroker
                });

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

        }

        function removeAssign() {
            $('#assign-broker-' + $scope.idOrder).remove();
        }

        function showAssignMessage(response) {
            if (typeof response.data.messages !== 'undefined') {
                response.data.messages.forEach((messageObj) => {
                    const translatedMessage = $translate.instant('orders.messages.' + messageObj.message);
                    utilsService.displayMessage(messageObj.code, translatedMessage);
                    removeAssign();
                    if(typeof $scope.onUpdate !== 'undefined'){
                        $scope.onUpdate();
                    }
                });
            }
        }
    }
})();
