'use strict';

var _keys = require('babel-runtime/core-js/object/keys');

var _keys2 = _interopRequireDefault(_keys);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Crypto = require('crypto');
var Url = require('url');
var queryParser = require('querystring');
var _memoryFileMap = {};

var MemoryFile = function () {
  (0, _createClass3.default)(MemoryFile, null, [{
    key: 'get',
    value: function get(name) {
      return _memoryFileMap[name];
    }
  }, {
    key: 'dump',
    value: function dump() {
      return (0, _keys2.default)(_memoryFileMap);
    }
  }]);

  function MemoryFile(fileName, content) {
    (0, _classCallCheck3.default)(this, MemoryFile);

    var rHttpHeader = /^(https?|taobao|qap):\/\/(?!.*your_current_ip)/i;
    if (rHttpHeader.test(fileName)) {
      var query = queryParser.parse(Url.parse(fileName).query);
      if (query['_wx_tpl']) {
        this.url = normalize(query['_wx_tpl']);
        this.name = this.url.replace(rHttpHeader, '');
      } else {
        this.url = normalize(fileName);
        this.name = this.url.replace(rHttpHeader, '');
      }
    } else {
      this.name = fileName.replace(/^(https?|taobao|qap):\/\/(.*your_current_ip):(\d+)\//i, 'file://');
    }
    if (this.name.charAt(this.name.length - 1) === '?') {
      this.name = this.name.substring(0, this.name.length - 1);
    }
    var md5 = Crypto.createHash('md5');
    md5.update(content);
    var md5Str = md5.digest('hex');
    var key = this.name.split('?')[0] + '|' + md5Str;
    if (_memoryFileMap[this.name]) {
      _memoryFileMap[this.name].content = content;
      return _memoryFileMap[this.name];
    } else if (_memoryFileMap[key]) {
      _memoryFileMap[key].content = content;
      return _memoryFileMap[key];
    } else {
      this.content = content;
    }
    this.md5 = md5Str;
    _memoryFileMap[this.name] = this;
    _memoryFileMap[key] = this;
  }

  (0, _createClass3.default)(MemoryFile, [{
    key: 'getContent',
    value: function getContent() {
      return this.content;
    }
  }, {
    key: 'getUrl',
    value: function getUrl() {
      return '/source/' + this.name;
    }
  }]);
  return MemoryFile;
}();

module.exports = MemoryFile;

function normalize(url) {
  var urlObj = Url.parse(url);
  if (urlObj.query) {
    urlObj.query = queryParser.stringify(queryParser.parse(urlObj.query));
    urlObj.search = '?' + urlObj.query;
  }
  return urlObj.format();
}