'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var nodejs_fs = require('../nodejs/fs.js');
var nodejs_http = require('../nodejs/http.js');
var nodejs_path = require('../nodejs/path.js');

function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function postFile(fileDataInfo, fileKeyValue, options) {
  return new Promise(function (resolve, reject) {
    if (!options) {
      console.log('[publish] failed. 需要 options');
      return;
    }
    var req = nodejs_http.getHttp().request(options, function (res) {
      // res.setEncoding("utf8");
      res.on('data', function (chunk) {
        var result = {};
        try {
          result = JSON.parse(chunk);
        } catch (_a) {}
        console.log('[postFile] result: ', result);
        resolve(result);
      });
    });
    req.on('error', function (e) {
      console.log("[postFile] problem with request: ".concat(e.message));
      reject(e);
    });
    var boundaryKey = Math.random().toString(16);
    var endData = "\r\n----".concat(boundaryKey, "--");
    var dataLength = 0;
    var dataArr = [];
    var _iterator = _createForOfIteratorHelper(fileDataInfo),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _item2 = _step.value;
        var dataInfo = "\r\n----".concat(boundaryKey, "\r\n") + "Content-Disposition: form-data; name=\"".concat(_item2.urlKey, "\"\r\n\r\n").concat(_item2.urlValue);
        var dataBinary = Buffer.from(dataInfo, 'utf-8');
        dataLength += dataBinary.length;
        dataArr.push({
          dataInfo: dataInfo
        });
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    var files = [];
    var _iterator2 = _createForOfIteratorHelper(fileKeyValue),
      _step2;
    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var _item3 = _step2.value;
        var content = "\r\n----".concat(boundaryKey, "\r\n") + 'Content-Type: application/octet-stream\r\n' + "Content-Disposition: form-data; name=\"".concat(_item3.urlKey, "\"; filename=\"").concat(nodejs_path.getPath().basename(_item3.urlValue), "\"\r\n") + 'Content-Transfer-Encoding: binary\r\n\r\n';
        // 当编码为ascii时，中文会乱码。
        var contentBinary = Buffer.from(content, 'utf-8');
        files.push({
          contentBinary: contentBinary,
          filePath: _item3.urlValue
        });
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }
    var contentLength = 0;
    for (var _i = 0, _files = files; _i < _files.length; _i++) {
      var item = _files[_i];
      var filePath = item.filePath;
      if (nodejs_fs.getFs().existsSync(filePath)) {
        var stat = nodejs_fs.getFs().statSync(filePath);
        contentLength += stat.size;
      } else {
        contentLength += Buffer.from('\r\n', 'utf-8').length;
      }
      contentLength += item.contentBinary.length;
    }
    req.setHeader('Content-Type', "multipart/form-data; boundary=--".concat(boundaryKey));
    req.setHeader('Content-Length', dataLength + contentLength + Buffer.byteLength(endData));
    // 将参数发出
    for (var _i2 = 0, _dataArr = dataArr; _i2 < _dataArr.length; _i2++) {
      var _item = _dataArr[_i2];
      req.write(_item.dataInfo);
    }
    var fileIndex = 0;
    var _doOneFile = function doOneFile() {
      req.write(files[fileIndex].contentBinary);
      var currentFilePath = files[fileIndex].filePath;
      if (nodejs_fs.getFs().existsSync(currentFilePath)) {
        // @ts-ignore
        var fileStream = nodejs_fs.getFs().createReadStream(currentFilePath, {
          bufferSize: 4 * 1024
        });
        fileStream.pipe(req, {
          end: false
        });
        fileStream.on('end', function () {
          fileIndex += 1;
          if (fileIndex === files.length) {
            req.end(endData);
          } else {
            _doOneFile();
          }
        });
      } else {
        req.write('\r\n');
        fileIndex += 1;
        if (fileIndex === files.length) {
          req.end(endData);
        } else {
          _doOneFile();
        }
      }
    };
    if (fileIndex === files.length) {
      req.end(endData);
    } else {
      _doOneFile();
    }
  });
}

exports.postFile = postFile;
