var angular = require('angular');
require('../modules');
var ionic = require('ionic');

var module = angular.module('commons.directives');

module.directive('sinoTextarea', function($ionicModal, $parse) {
  function link(scope, element, attrs, ngForm) {
    var ngModelGet = $parse(attrs.sinoTextareaModel),
      ngModelSet = ngModelGet.assign,
      title = element[0].innerText.replace('：', '');
    scope = ngForm? scope.$parent : scope;
    var newScope = scope.$new();
    newScope.title = title;
    newScope.bean = {};
    scope.$watch(attrs.sinoTextareaModel, function(value) {
      newScope.bean.value = value;
    });
    scope.$watch(attrs.ngReadonly, function(readonly) {
      newScope.readonly = readonly;
    });

    element.on('focus', function(event) {
      event.preventDefault();
      event.stopPropagation();
    });

    var clicked = false;
    element.on('click', function(event) {
      if (newScope.readonly || clicked) {
        return;
      }
      clicked = true;
      event.preventDefault();
      event.stopPropagation();
      scope.$apply(function() {
        $ionicModal.fromTemplateUrl(
        'views/commons/directives/sinoTextareaModal.tpl.html', {
          scope: newScope,
          animate: 'slide-in-up'
        }).then(function(modal) {
          newScope.modal = modal;
          newScope.modal.show();
          clicked = false;
        });
      });
    });
    
    newScope.close = function() {
      newScope.modal.hide().then(function() {
        newScope.modal.remove();
      });
    };
    newScope.goBack = function() {
      newScope.close();
    };
    newScope.ok = function() {
      newScope.close();
    };

    newScope.$watch('bean.value', function(value) {
      ngModelSet(scope, value);
    });

    scope.$on('$destroy', function() {
      if (newScope.modal) {
        newScope.modal.hide();
      }
    });
  }

  return {
    restrict: 'A',
    require:'?^form',
    compile: function(element, attrs) {
      if (ionic.Platform.isWebView()) {
        return;
      }
      if (!ionic.Platform.isAndroid() && !ionic.Platform.isIOS()) {
        return;
      }
      var textarea = element[0].querySelector('textarea');
      element[0].setAttribute('ng-readonly', textarea.getAttribute('ng-readonly'));
      textarea.removeAttribute('ng-readonly');
      textarea.setAttribute('readonly', 'readonly');
      attrs.$set('sinoTextareaModel', textarea.getAttribute('ng-model'));
      return link;
    }
  };
});
