'use strict';
define(function() {
  var emailWriter = function(
    ngDialog,
    UsersFactory,
    gaDomUtils,
    FunctionFactory,
    gaJsUtils,
    taOptions,
    $rootScope,
    $filter
  ) {
    return {
      templateUrl: 'js/XG/modules/common/views/directives/email_writer.html',
      scope: {
        title: '=?', // email title default
        content: '=?', //email content default
        buttonTitle: '=?', //button title default
        contentUrl: '=?',
      },
      restrict: 'EA',
      link: function(scope, element, attr) {
        if (!scope.buttonTitle) {
          scope.buttonTitle = 'mail_writer.title';
        }
        /**
         * reset taOptions of toolbar
         * @type {*[]}
         */
        taOptions.toolbar = [
          [
            'h1',
            'h2',
            'h3',
            'h4',
            'h5',
            'h6',
            'bold',
            'italics',
            'underline',
            'strikeThrough',
            'ul',
            'ol',
            'insertLink',
          ],
        ];

        /**
         * init data
         */
        var init = function() {
          scope.email = {};
          scope.recipients = [];
          scope.recipients_cc = [];
          scope.recipients_bcc = [];
          scope.copy_forself = false;
          /**
           * Email content and title default
           */
          if (scope.content) {
            scope.email.htmlVariable = scope.content;
          }
          if (scope.title) {
            scope.email.title = scope.title;
          }
          if (scope.contentUrl) {
            scope.email.htmlVariable =
              '<p><a href="' +
              scope.contentUrl +
              '">' +
              scope.contentUrl +
              '</a><br/></p>';
          }
        };
        init();

        scope.$on('urlsharingchanged', function(event, args) {
          scope.email.htmlVariable =
            '<p><a href="' + args + '">' + args + '</a><br/></p>';
        });

        /**
         * get liste users
         */
        UsersFactory.getactiveusers().then(function(res) {
          console.log(res.data);
          res.data.forEach(function(user) {
            user.url = 'img/user/default/user.png';
          });
          scope.usersCol = res.data;
        });

        var emailDialog;
        /**
         * open dialog Email
         * @returns {boolean}
         */
        scope.openModal = function() {
          /**
           * check emailCfg
           */
          if (
            !$rootScope.xgos.portal.sendMailCfg ||
            $rootScope.xgos.portal.sendMailCfg == null
          ) {
            gaJsUtils.errorMessage($filter('translate')('mail_writer.alert'));
            return false;
          }

          emailDialog = ngDialog.open({
            template:
              'js/XG/modules/common/views/directives/email_writer_dialog.html',
            className: 'ngdialog-theme-plain width1000 nopadding miniclose',
            closeByDocument: false,
            scope: scope,
          });
        };

        /**
         * send email
         */
        scope.sendEmail = function() {
          var recipients = scope.recipients.map(function(r) {
            return r.email;
          });

          var recipients_cc = [];
          scope.recipients_cc.forEach(function(recipient) {
            recipients_cc.push(recipient.email);
          });

          if (scope.copy_forself) {
            if (
              $rootScope.xgos.user.email &&
              $rootScope.xgos.user.email != ''
            ) {
              recipients_cc.push($rootScope.xgos.user.email);
            }
          }

          var recipients_bcc = [];
          scope.recipients_bcc.forEach(function(recipient) {
            recipients_bcc.push(recipient.email);
          });

          var mailDesc = [];
          mailDesc.push({
            name: 'mailTo',
            type: 'cst',
            value: recipients,
          });
          mailDesc.push({
            name: 'mailCC',
            type: 'cst',
            value: recipients_cc,
          });
          mailDesc.push({
            name: 'mailBCC',
            type: 'cst',
            value: recipients_bcc,
          });
          mailDesc.push({
            name: 'mailSubject',
            type: 'cst',
            value: scope.email.title,
          });
          mailDesc.push({
            name: 'mailContent',
            type: 'cst',
            value: scope.email.htmlVariable,
          });

          gaDomUtils.showGlobalLoader();
          FunctionFactory.execute(
            { parameters: mailDesc },
            'sendMail',
            'ja'
          ).then(
            function(res) {
              emailDialog.close();
              init();
              gaDomUtils.hideGlobalLoader();
              if (res.data === 'true') {
                gaJsUtils.successMessage(
                  $filter('translate')('mail_writer.success')
                );
              } else
                gaJsUtils.errorMessage(
                  $filter('translate')('mail_writer.error')
                );
            },
            function() {
              emailDialog.close();
              gaDomUtils.hideGlobalLoader();
            }
          );
        };

        /**
         * return button send value
         * @returns {boolean}
         */
        scope.renderValid = function() {
          var res = true;

          if (
            scope.email.title &&
            scope.email.htmlVariable &&
            scope.email.title != '' &&
            scope.email.htmlVariable != '' &&
            scope.recipients.length > 0
          ) {
            res = false;
          }
          return res;
        };

        scope.users = {};
        /**
         * get users from directive 'user-picker'
         * update la liste of recipients
         */
        scope.$watch(
          'users',
          function(users) {
            if (scope.users == {}) return false;
            if (scope.users.to) {
              var logins = [];
              scope.recipients.forEach(function(recipient) {
                logins.push(recipient.login);
              });
              scope.users.to.forEach(function(user) {
                var contains = false;
                logins.forEach(function(login) {
                  if (login == user.login) {
                    contains = true;
                  }
                });
                if (contains == false) {
                  user.url = 'img/user/default/user.png';
                  scope.recipients.push(user);
                  logins.push(user.login);
                }
              });
            }

            if (scope.users.cc) {
              logins = [];
              scope.recipients_cc.forEach(function(recipient) {
                logins.push(recipient.login);
              });
              scope.users.cc.forEach(function(user) {
                var contains = false;
                logins.forEach(function(login) {
                  if (login == user.login) {
                    contains = true;
                  }
                });
                if (contains == false) {
                  user.url = 'img/user/default/user.png';
                  scope.recipients_cc.push(user);
                  logins.push(user.login);
                }
              });
            }

            if (scope.users.bcc) {
              var logins = [];
              scope.recipients_bcc.forEach(function(recipient) {
                logins.push(recipient.login);
              });
              scope.users.bcc.forEach(function(user) {
                var contains = false;
                logins.forEach(function(login) {
                  if (login == user.login) {
                    contains = true;
                  }
                });
                if (contains == false) {
                  user.url = 'img/user/default/user.png';
                  scope.recipients_bcc.push(user);
                  logins.push(user.login);
                }
              });
            }
          },
          1
        );

        /**
         * check string value is email address
         * @returns {boolean}
         */
        var validEmail = function(recipients) {
          for (var i = 0; i < recipients.length; i++) {
            if (!recipients[i].url) {
              recipients[i].url = 'img/user/default/user.png';
            }
            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            if (reg.test(recipients[i].email) == false) {
              recipients.splice(i, 1);
            }
          }
        };

        /**
         * check email address valid
         */
        scope.$watch(
          'recipients',
          function(recipients) {
            validEmail(scope.recipients);
          },
          1
        );

        scope.$watch(
          'recipients_cc',
          function(recipients_cc) {
            validEmail(scope.recipients_cc);
          },
          1
        );

        scope.$watch(
          'recipients_bcc',
          function(recipients_bcc) {
            validEmail(scope.recipients_bcc);
          },
          1
        );
      },
    };
  };

  emailWriter.$inject = [
    'ngDialog',
    'UsersFactory',
    'gaDomUtils',
    'FunctionFactory',
    'gaJsUtils',
    'taOptions',
    '$rootScope',
    '$filter',
  ];
  return emailWriter;
});
