// eTranslation stuff
var sedAngularTrans = angular.module('sedAngularTrans', []);

sedAngularTrans
.controller('TranslationCtrl',
  ['$scope', '$timeout', '$window', 'wbeTranslationSvc', 
    function ($scope, $timeout, $window, wbeTranslationSvc) 
    {
      var languageMap = {
        "nob": "no",
        "deu": "de",
        "fin": "fi",
        "swe": "sv",
        "por": "pt",
        "bul": "bg",
        "Maltese": "mt",
        "ell": "el",
        "lit": "lt",
        "eng": "en",
        "hrv": "hr",
        "lav": "lv",
        "ita": "it",
        "fra": "fr",
        "hun": "hu",
        "spa": "es",
        "est": "et",
        "ces": "cs",
        "slk": "sk",
        "slv": "sl",
        "pol": "pl",
        "ron": "ro",
        "dan": "da",
        "nld": "nl",
      };
      var countries = {
    	    "BG": "BULGARIAN (БЪЛГАРСКИ)",
    	  	"CS": "CZECH (ČEŠTINA)",
			"DA": "DANISH (DANSK)",
			"DE": "GERMAN (DEUTSCH)",
			"EL": "GREEK (ΕΛΛΗΝΙΚΆ)",
			"EN": "ENGLISH",
			"ES": "SPANISH (ESPAÑOL)",
			"ET": "ESTONIAN (EESTI KEEL)",
    	  	"FI": "FINNISH (SUOMI)",
    	  	"FR": "FRENCH (FRANÇAIS)",
			"HR": "CROATIAN (HRVATSKI)",
			"HU": "HUNGARIAN (MAGYAR)",
			"IT": "ITALIAN (ITALIANO)",
			"LT": "LITHUANIAN (LIETUVIŲ KALBA)",
			"LV": "LATVIAN (LATVIEŠU VALODA)",
			"MT": "MALTESE (MALTI)",
    	  	"NL": "DUTCH (NEDERLANDS)",
    	  	"NO": "NORWEGIAN (NORSK)",
			"PL": "POLISH (POLSKI)",
			"PT": "PORTUGUESE (PORTUGUÊS)",
			"RO": "ROMANIAN (ROMÂNĂ)",
			"SK": "SLOVAK (SLOVENSKÉHO)",
			"SL": "SLOVENIAN (SLOVINSKÝ)",
			"SV": "SWEDISH (SVENSKA)",
        };
      
      var urlParams;
      (window.onpopstate = function () {
          var match,
              pl     = /\+/g,  // Regex for replacing addition symbol with a space
              search = /([^&=]+)=?([^&]*)/g,
              decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
              query  = window.location.search.substring(1);

          urlParams = {};
          while (match = search.exec(query))
             urlParams[decode(match[1])] = decode(match[2]);
      })();
      
      // create print section
      var printSection = document.getElementById('printSection');
      if (!printSection) {
        printSection = document.createElement('div');
        printSection.id = 'printSection';
        document.body.appendChild(printSection);
        printSection.innerHTML = '';
      }

      // init vars
      $scope.loaded = false;

      $scope.textSource = $window.sessionStorage.getItem(urlParams.id);

      $scope.countries = countries;

      $scope.sedName = urlParams.sed;

      $scope.fieldName = urlParams.field;

      $scope.countrySource = 'EN';

	  $scope.countryTarget = 'FR';

      $scope.loaded = true;

      // translate
      $scope.translate = function () {
        $scope.isBusy = true;

        var translation = {
          //id: $stateParams.id,
          id: urlParams.id,
          text: $scope.textSource,
          from: $scope.countrySource.toUpperCase(),
          to: $scope.countryTarget.toUpperCase()
        };

        wbeTranslationSvc.translate(translation).then(function (result) {
          $scope.textTarget = result.translatedText;
          $window.sessionStorage.removeItem(urlParams.id);
          $scope.isBusy = false;
        }, function (error) {
          $scope.isBusy = false;
          alert('Error getting translation: '+error.error);
        });
      }

      // print
      $scope.print = function () {
        var translationSection = document.getElementById('translationSection');

        if (translationSection) {
          $scope.isBusy = true;

          $timeout(function () {
            printSection.innerHTML = '';
            printElement(translationSection);
            $scope.isBusy = false;
          }, 1000);

        }
      }

      function printElement(elem) {
        var domClone = elem.cloneNode(true);
        printSection.appendChild(domClone);
        window.print();
      }

      // auto detect language
      function detectLanguage(text) {
        var language = franc(text);
        if (language) {
          return languageMap[language];
        } else
          return "EL";
      }

      // copy
      $scope.copy = function (element) {
        wbeTranslationSvc.copyToClipBoard(element);
      }
      
    }]);

sedAngularTrans
.factory('wbeTranslationSvc', ['$rootScope', '$compile', '$document', '$http', '$q', '$location',
  function ($rootScope, $compile, $document, $http, $q, $location) {

    return {
      translate: translate,
      copyToClipBoard: copyToClipBoard
    };

    function translate(translation) {
      var deferred = $q.defer();
      //var url = location.protocol + "//" + window.location.hostname + ":8081/translation/"
      //var url = 'http://52.166.23.43:8081/translation/';
      var url;
      if ($location.protocol() === "file") 
    	  url = 'http://rinatestdev.westeurope.cloudapp.azure.com:8081/translation/';
      else 
    	  url = 'https://dev.eessi-project.eu:81/translation/';


      $http.post(url, translation) // ,{timeout: 10000}
        .success(function (data) {
          deferred.resolve(data);
        }).error(function (error) {
        if(error)
        	console.log("Error is: "+error.description);
        if (!error)
          //error = {error: WB_CONSTANTS.ETRANSLATION.Server_not_started};
        	error = {error: 'Server not started'};
        //else if (error.description.contains(WB_CONSTANTS.ETRANSLATION.Request_timed_out)) {
        else if (error.description.includes('Request timed out')) {
          error = {error: 'Request timed out'};
        }
        else{
          error = {error: error.description};
        }
        deferred.reject(error)
      });
      return deferred.promise;
    }

    function copyToClipBoard(element) {
      var copiedElement = angular.element('<span id="copyToClipBoard">' + element + '</span>');
      var body = $document.find('body').eq(0);
      body.append($compile(copiedElement)($rootScope));

      var clipboardElement = angular.element(document.getElementById('copyToClipBoard'));
      var range = document.createRange();
      range.selectNode(clipboardElement[0]);

      window.getSelection().removeAllRanges();
      window.getSelection().addRange(range);

      document.execCommand('copy');
      window.getSelection().removeAllRanges();

      copiedElement.remove();
    }
  }]);