var angular = require('angular');
require('../modules');
require('jsUtil');
require('../directives/$toast');

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

module.factory('DiscussService', function($q, $ionicActionSheet, $toast, $window,
  CoreAppConfig, fileService, AudioFileService) {
  var service;
  service = {
    /**
     * 解析图片路径，返回图片的服务器获取路径。
     * @param  {String} src
     * @return {String}
     */
    parseImageSrc: function(src) {
      return CoreAppConfig.serverUrl + src;
    },
    /**
     * 成功删除缓存图片的处理。
     */
    deleteCacheFileSuccess: function() {
      console.log('删除缓存图片成功');
    },
    /**
     * 删除缓存图片失败的处理。
     */
    deleteCacheFileFailure: function() {
      console.log('删除缓存图片失败');
    },
    /**
     * 上传图片，上传成功后进行图片缓存的删除处理。
     * @param  {FileEntry} fileEntry
     * @return {Promise}
     */
    uploadImage: function(fileEntry) {
      var options = {
        mimeType: 'image/jpeg',
        fileName: fileEntry.name + '.jpg',
        params: {
          category: 'mission-images'
        }
      };
      return service.getFileEntry(fileEntry).then(function(fileEntry) {
        return fileService.upload(fileEntry.toURL(), options).then(function(response) {
          fileService.deleteCacheFile(fileEntry).then(service.deleteCacheFileSuccess,
            service.deleteCacheFileFailure);
          return $q.when(response);
        }, function() {
          $toast.showLongCenter('上传失败，请检查网络连接。');
          return $q.reject();
        });
      }, function() {
        $toast.showLongCenter('从缓存中获取图片失败。');
        return $q.reject();
      });

    },

    getFileEntry: function(fileEntry) {
      var deferred = $q.defer();
      if (jsUtil.isString(fileEntry)) {
        fileService.resolveURLtoFileEntry(fileEntry).then(function(fileEntry) {
          deferred.resolve(fileEntry);
        }, function() {
          deferred.reject();
        });
      } else {
        deferred.resolve(fileEntry);
      }

      return deferred.promise;
    },

    uploadAudio: function(media) {
      var fileId;
      var promise = AudioFileService.upload(media).then(function(_response) {
        var file = JSON.parse(_response.response)[0];
        fileId = file.id;
        return fileId;
      }).then(function(fileId) {
        var duration = media.getDuration();
        if (duration <= 0) {
          duration = media.duration / 1000;
        }
        var playAudioHtml = '<div audio-player="' + fileId + '" duration="' + duration + '"></div>';
        return playAudioHtml;
      });

      return promise;
    },
    /**
     * 图片获取成功的处理，将图片写入缓存，目录为/images/下。
     * @param  {String} fileURL 图片文件的url
     * @return {Promise}
     */
    onGetPictureSuccess: function(fileURL) {
      var imageId = fileService.guid();
      return fileService.resolveURLtoFileEntry(fileURL).then(function() {
        return fileService.copyFile(fileURL, 'images', imageId + '.jpg');
      }, function() {
        return $q.reject();
      });
    },
    /**
     * 缓存图片成功的处理。
     * @param  {FileEntry}   fileEntry
     * @param  {Function} callback  回调函数
     */
    cacheImageSuccess: function(fileEntry, callback) {
      var width = 150,
        height = 150;

      window.Thumbnails.thumbnail(fileEntry.toURL(), width, height, function success(path) {
        var imageId = path.match(/\/([a-z0-9-]+)\.jpg$/i)[1];
        if($window.device.platform === 'Android') {
          path = 'file:///' + path;
        }
        var imageHtml = '<img class="image-view" origin-src="' + fileEntry.toURL() + '" src="' + path + '" image-id="' + imageId + '" style="max-width:150px;max-height:150px;">';
        callback(imageHtml);
      }, function fail(error) {
        console.error(error);
      });
    },
    /**
     * 重发消息
     * @param  {Function} callback 回调函数
     */
    reSend: function(callback) {
      $ionicActionSheet.show({
        buttons: [{
          text: '重发消息'
        }],
        cancelText: '取消',
        cancel: function() {
          return true;
        },
        buttonClicked: function() {
          callback();
          return true;
        }
      });
    }
  };

  return service;
});
