'use strict';

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

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.requestList = requestList;
exports.valueList = valueList;
exports.urlList = urlList;
exports.fileList = fileList;
exports.nextDataList = nextDataList;
exports.getDataList = getDataList;
exports.removeDataList = removeDataList;

var _bluebird = require('bluebird');

var _http = require('http');

var _http2 = _interopRequireDefault(_http);

var _https = require('https');

var _https2 = _interopRequireDefault(_https);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _ = require('../../');

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

function requestList(obj, tplPath, match, jsonPage) {
  var p = new _bluebird.Promise(function (resolve) {
    _.cmsData.sql.executeQuery(tplPath, match, jsonPage).then(function (data) {
      if (!jsonPage['abe_source']) {
        jsonPage['abe_source'] = {};
      }
      jsonPage['abe_source'][obj.key] = data;
      if (!obj.editable) {
        if (obj['max-length']) {
          jsonPage[obj.key] = data.slice(0, obj['max-length']);
        } else {
          jsonPage[obj.key] = data;
        }
      } else if (jsonPage[obj.key] == null && obj.prefill) {
        if (obj['prefill-quantity'] && obj['max-length']) {
          jsonPage[obj.key] = data.slice(0, obj['prefill-quantity'] > obj['max-length'] ? obj['max-length'] : obj['prefill-quantity']);
        } else if (obj['prefill-quantity']) {
          jsonPage[obj.key] = data.slice(0, obj['prefill-quantity']);
        } else if (obj['max-length']) {
          jsonPage[obj.key] = data.slice(0, obj['max-length']);
        } else {
          jsonPage[obj.key] = data;
        }
      }

      resolve(jsonPage);
    });
  });

  return p;
}

function valueList(obj, match, jsonPage) {
  var p = new _bluebird.Promise(function (resolve) {
    var value = _.cmsData.sql.getDataSource(match);

    if (value.indexOf('{') > -1 || value.indexOf('[') > -1) {
      try {
        value = JSON.parse(value);

        jsonPage['abe_source'][obj.key] = value;
      } catch (e) {
        jsonPage['abe_source'][obj.key] = null;
        console.log('Error ' + value + '/is not a valid JSON', '\n' + e);
      }
    }
    resolve();
  });

  return p;
}

function urlList(obj, tplPath, match, jsonPage) {
  var p = new _bluebird.Promise(function (resolve) {
    if (obj.autocomplete !== true && obj.autocomplete !== 'true') {
      var host = obj.sourceString;
      host = host.split('/');
      var httpUse = _http2.default;
      var defaultPort = 80;
      if (host[0] === 'https:') {
        httpUse = _https2.default;
        defaultPort = 443;
      }
      host = host[2].split(':');

      var pathSource = obj.sourceString.split('//');
      if (pathSource[1] != null) {
        pathSource = pathSource[1].split('/');
        pathSource.shift();
        pathSource = '/' + pathSource.join('/');
      } else {
        pathSource = '/';
      }
      var options = {
        hostname: host[0],
        port: host[1] != null ? host[1] : defaultPort,
        path: pathSource,
        method: 'GET',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': 0
        }
      };

      var body = '';

      var localReq = httpUse.request(options, function (localRes) {
        localRes.setEncoding('utf8');
        localRes.on('data', function (chunk) {
          body += chunk;
        });
        localRes.on('end', function () {
          try {
            if (typeof body === 'string') {
              var parsedBody = JSON.parse(body);
              if ((typeof parsedBody === 'undefined' ? 'undefined' : _typeof(parsedBody)) === 'object' && Object.prototype.toString.call(parsedBody) === '[object Array]') {
                jsonPage['abe_source'][obj.key] = parsedBody;
              } else if ((typeof parsedBody === 'undefined' ? 'undefined' : _typeof(parsedBody)) === 'object' && Object.prototype.toString.call(parsedBody) === '[object Object]') {
                jsonPage['abe_source'][obj.key] = [parsedBody];
              }
            } else if ((typeof body === 'undefined' ? 'undefined' : _typeof(body)) === 'object' && Object.prototype.toString.call(body) === '[object Array]') {
              jsonPage['abe_source'][obj.key] = body;
            } else if ((typeof body === 'undefined' ? 'undefined' : _typeof(body)) === 'object' && Object.prototype.toString.call(body) === '[object Object]') {
              jsonPage['abe_source'][obj.key] = body;
            }
          } catch (e) {
            console.log('Error ' + obj.sourceString + ' is not a valid JSON', '\n' + e);
          }
          resolve();
        });
      });

      localReq.on('error', function (e) {
        console.log(e);
      });

      // write data to request body
      localReq.write('');
      localReq.end();
    } else {
      jsonPage['abe_source'][obj.key] = obj.sourceString;
      resolve();
    }
  });

  return p;
}

function fileList(obj, tplPath, match, jsonPage) {
  var p = new _bluebird.Promise(function (resolve) {
    jsonPage['abe_source'][obj.key] = _.cmsData.file.get(_path2.default.join(_.config.root, obj.sourceString));
    resolve();
  });

  return p;
}

function nextDataList(tplPath, jsonPage, match, onlyDynamicSelect) {
  var p = new _bluebird.Promise(function (resolve) {
    if (jsonPage['abe_source'] == null) {
      jsonPage['abe_source'] = {};
    }

    var obj = _.cmsData.attributes.getAll(match, jsonPage);
    obj = _.cmsData.attributes.sanitizeSourceAttribute(obj, jsonPage);

    var type = _.cmsData.sql.getSourceType(obj.sourceString);

    switch (type) {
      case 'request':
        if (onlyDynamicSelect && obj.editable) {
          resolve();
        } else {
          requestList(obj, tplPath, match, jsonPage).then(function (jsonPage) {
            resolve(jsonPage);
          }).catch(function (e) {
            console.log('[ERROR] source.js requestList', e);
          });
        }
        break;
      case 'value':
        valueList(obj, match, jsonPage).then(function () {
          resolve();
        }).catch(function (e) {
          console.log('[ERROR] source.js valueList', e);
        });
        break;
      case 'url':
        urlList(obj, tplPath, match, jsonPage).then(function () {
          resolve();
        }).catch(function (e) {
          console.log('[ERROR] source.js urlList', e);
        });
        break;
      case 'file':
        fileList(obj, tplPath, match, jsonPage).then(function () {
          resolve();
        }).catch(function (e) {
          console.log('[ERROR] source.js fileList', e);
        });
        break;
      default:
        resolve();
        break;
    }
  });

  return p;
}

function getDataList(tplPath, text, jsonPage) {
  var onlyDynamicSelect = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;

  var p = new _bluebird.Promise(function (resolve) {

    var promises = [];
    var matches = _.cmsData.regex.getTagAbeTypeRequest(text);
    Array.prototype.forEach.call(matches, function (match) {
      promises.push(nextDataList(tplPath, jsonPage, match[0], onlyDynamicSelect));
    });

    _bluebird.Promise.all(promises).then(function () {
      resolve();
    }).catch(function (e) {
      console.error('source.js getDataList', e);
    });
  }).catch(function (e) {
    console.error('source.js getDataList', e);
  });

  return p;
}

function removeDataList(text) {
  var listReg = /({{abe.*type=[\'|\"]data.*}})/g;

  return text.replace(listReg, '');
}