var angular = require('angular'),
  _ = require('jsUtil');

require('../modules');

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

module.factory('AffixService',function($http, $q) {
  var DOC = 'doc', DOCX = 'docx';


  function queryAffix(tableId, tableName, affixIds) {
    var url = '/affix';
    return $http.get(url, {
      timeout: 15000,
      params: {
        tableName: tableName,
        tableId: tableId,
        affixIds: affixIds
      }
    }).then(function(response) {
      return response.data;
    });
  }

  function getTitle(affixId, title, fileType){
    if (fileType.toLowerCase() !== DOCX &&
      fileType.toLowerCase() !== DOC) {
      return $q.when(getTitleByFileType(title, fileType));
    } else {
      var url = '/affix/fileType/' + affixId;
      return $http.get(url, {
        timeout: 15000
      }).then(function(response) {
        var data = response.data,
          _fileType = data.fileType;
        title = getTitleByFileType(title, fileType);
        return title.replace(new RegExp(fileType + '$'), _fileType);
      });
    }
  }

  function getTitleByFileType(title, fileType) {
    var fileTypeSuffix = '.' + fileType;
    return (title.indexOf(fileTypeSuffix) === -1) ? (title + fileTypeSuffix) : title;
  }

  return {
    queryAffix: queryAffix,
    getTitle: getTitle,
    getTitleByFileType: getTitleByFileType
  };
});
