var angular = require('angular'),
  _ = require('jsUtil');
require('../modules');
require('../../flow/services/WorkflowTransfer');
require('./DefaultWorkflowRequest');
require('../../linker/services/LinkerService');
require('../../flow/services/NotionService');
require('../../../commons/services/CommonService');

var module = angular.module('flowmodulebutton.services');

module.factory('OpenQzNotionService', function($rootScope, CommonService, DefaultWorkflowParam) {
  var $scope = $rootScope.$new();

  var service = {
    openWriteNotion: openWriteNotion,
    openRequireNotion: openRequireNotion
  };

  $scope.closeNotion = closeNotion;

  return service;

  function openNotion() {
    if (!$scope.modal) {
      CommonService.createModal('views/flow/qzNotion.tpl.html', $scope).then(function(modal) {
        $scope.modal = modal;
        $scope.modal.show();
      });
    } else {
      $scope.modal.show();
    }
  }

  function closeNotion() {
    if ($scope.modal) {
      $scope.modal.remove();
      $scope.modal = null;
    }
  }

  function openRequireNotion() {
    DefaultWorkflowParam.get().tempNotions.forEach(function(tempNotion) {
      if (tempNotion.requireFn()) {
        DefaultWorkflowParam.get().tempNotion = tempNotion;
        openNotion();
      }
    });
  }

  function openWriteNotion(text) {
    DefaultWorkflowParam.get().tempNotions.forEach(function(tempNotion) {
      if (text.indexOf(tempNotion.title) != -1) {
        DefaultWorkflowParam.get().tempNotion = tempNotion;
        openNotion();
      }
    });
  }


});
