(function () {
    global.dashModule
        .directive('editProfile', editProfileDirective)
        .controller('editProfileCtrl', ['$scope', '$', '$http', '$translate', 'utilsService', editProfileCtrl]);

    function editProfileDirective() {
        return {
            restrict: 'E',
            templateUrl: 'profileSettings/html/EditProfileTemplate'
        };
    }

    function editProfileCtrl($scope, $, $http, $translate, utilsService) {
        $scope.saveProfile = saveProfile;
        $scope.getProfile = getProfile;
        $scope.saveCompany = saveCompany;
        $scope.isCompanyAdmin = isCompanyAdmin;
        $scope.idUser = global.getParameterByName('idUser') || 0;

        function isCompanyAdmin(){
            return $scope.data && (parseInt($scope.data.isCompanyAdmin) === 1 || $scope.data.userType === 'broker');
        }

        function getProfile(){
            const params = $.param({
                idUser: $scope.idUser
            });

            $http({
                method: 'POST',
                data: params,
                url: 'v2/profileSettings/api/getProfileInfo'
            }).then(setProfile, utilsService.onHttpError);
        }

        function setProfile(response){
            if (response.data) {
                $scope.data = response.data;
            }
        }

        function saveProfile() {
            const params = $.param({
                idUser: $scope.idUser,
                profile: JSON.stringify($scope.data)
            });

            $http({
                method: 'POST',
                data: params,
                url: 'v2/profileSettings/api/saveProfileInfo'
            }).then(showConfirmationMessage, utilsService.onHttpError);
        }

        function saveCompany() {
            const params = $.param({
                companyInfo: JSON.stringify({
                    idCompany: $scope.data.idCompany,
                    companyName: $scope.data.companyName,
                    vatCode: $scope.data.vatCode
                })
            });

            $http({
                method: 'POST',
                data: params,
                url: 'v2/profileSettings/api/saveCompanyInfo'
            }).then(showConfirmationMessage, utilsService.onHttpError);
        }

        function showConfirmationMessage(response) {
            if(response.data && response.data.messages) {
                response.data.messages.forEach(messageData => {
                    const message = $translate.instant('profile.forms.messages.' + messageData.message);
                    utilsService.displayMessage(messageData.code, message);
                });
            }
        }
    }
})();
