'use strict';

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

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _winstonLogs = require('./winstonLogs');

var _winstonLogs2 = _interopRequireDefault(_winstonLogs);

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

var portscanner = require('portscanner');

// Checks the status of a single port
// returns 'closed' if port is available
// returns 'open' if port is not available
/*
 * *******************************************************************************
 *  * Copyright (c) 2018 Edgeworx, Inc.
 *  *
 *  * This program and the accompanying materials are made available under the
 *  * terms of the Eclipse Public License v. 2.0 which is available at
 *  * http://www.eclipse.org/legal/epl-2.0
 *  *
 *  * SPDX-License-Identifier: EPL-2.0
 *  *******************************************************************************
 *
 */

/**
 * @file appUtils.js
 * @author Zishan Iqbal
 * @description This file includes the utility functions relevant to IOAuthoring;
 */

var checkPortAvailability = function checkPortAvailability(port) {
  return portscanner.checkPortStatus(port).then(function (status) {
    return status;
  });
};

var isArray = function isArray(object) {
  return Object.prototype.toString.call(object) === '[object Array]';
};
/**
 * @desc generates a random String of 64 size
 * @param - none
 * @return String - returns random string
 */
var generateAccessToken = function generateAccessToken() {
  var token = '',
      i;
  for (i = 0; i < 8; i++) {
    token += (0 + (Math.floor(Math.random() * Math.pow(2, 31)) + 1).toString(16)).slice(-8).substr(-8);
  }
  return token;
};
/**
 * @desc generates a random String of the size specified by the input param
 * @param Integer - size
 * @return String - returns random string
 */
var generateRandomString = function generateRandomString(size) {

  var randString = "";
  var possible = "2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ";

  for (var i = 0; i < size; i++) {
    randString += possible.charAt(Math.floor(Math.random() * possible.length));
  }return randString;
};

var isFileExists = function isFileExists(filePath) {
  if (_path2.default.extname(filePath).indexOf(".") >= 0) {
    if (_fs2.default.existsSync(filePath)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
};

var isValidPort = function isValidPort(port) {
  port = Number(port);
  if (Number.isInteger(port)) {
    if (port >= 0 && port < 65535) return true;
  }
  return false;
};

var isValidEmail = function isValidEmail(email) {
  var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
};

var isValidName = function isValidName(name) {
  var re = /^([a-zA-Z0-9]+)$/;
  return re.test(name);
};

var isValidDomain = function isValidDomain(domain) {
  var re = /^((?:(?:(?:\w[\.\-\+]?)*)\w)+)((?:(?:(?:\w[\.\-\+]?){0,62})\w)+)\.(\w{2,6})$/;
  return re.test(domain);
};

var isValidPublicIP = function isValidPublicIP(publicIP) {
  var re = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
  return re.test(publicIP);
};

var convertRelativePathToAbsolute = function convertRelativePathToAbsolute(filePath) {
  if (_path2.default.isAbsolute(filePath)) {
    return filePath;
  } else {
    return _path2.default.resolve(filePath);
  }
};

/**
 * @desc generates a random String of the size specified by the input param
 * @param Integer - size
 * @return String - returns random string
 */
var generateInstanceId = function generateInstanceId(size) {

  var randString = "";
  var possible = "2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ";

  for (var i = 0; i < size; i++) {
    randString += possible.charAt(Math.floor(Math.random() * possible.length));
  }return randString;
};

var getProperty = function getProperty(theObject, path, separator) {
  if (path) {
    try {
      separator = separator || '.';

      return path.replace('[', separator).replace(']', '').split(separator).reduce(function (obj, property) {
        return obj[property];
      }, theObject);
    } catch (err) {
      return undefined;
    }
  } else {
    return null;
  }
};

var onCreate = function onCreate(params, paramName, errorMsg, callback, modelObject) {
  if (modelObject) {
    if (paramName) {
      params[paramName] = modelObject;
    }
    callback(null, params);
  } else {
    callback('error', errorMsg);
  }
};

var onFind = function onFind(params, paramName, errorMsg, callback, modelObject) {
  if (modelObject) {
    if (paramName) {
      params[paramName] = modelObject;
    }
    callback(null, params);
  } else {
    callback('error', errorMsg);
  }
};

var onFindOptional = function onFindOptional(params, paramName, callback, modelObject) {
  if (modelObject && paramName) {
    params[paramName] = modelObject;
  }

  callback(null, params);
};

var onUpdate = function onUpdate(params, errorMsg, callback, updatedModels) {
  if (updatedModels.length > 0) {
    callback(null, params);
  } else {
    callback('error', errorMsg);
  }
};

var onDelete = function onDelete(params, errorMsg, callback, deletedModels) {
  if (deletedModels <= 0) {
    callback('error', errorMsg);
  } else {
    callback(null, params);
  }
};

var onDeleteOptional = function onDeleteOptional(params, callback, deletedModels) {
  callback(null, params);
};

var sendResponse = function sendResponse(response, err, successLabel, successValue, errorMessage) {
  var res = {
    'timestamp': new Date().getTime()
  };

  response.status(200);
  if (err) {
    _winstonLogs2.default.error(errorMessage);
    res['status'] = 'failure';
    res['errormessage'] = errorMessage;
  } else {
    _winstonLogs2.default.info("Success");
    res['status'] = 'ok';
    if (successLabel || successValue) {
      res[successLabel] = successValue;
    }
  }
  response.send(res);
};

var sendMultipleResponse = function sendMultipleResponse(response, err, successLabelArr, successValueArr, errorMessage) {
  var res = {
    'timestamp': new Date().getTime()
  };

  response.status(200);
  if (err) {
    _winstonLogs2.default.error(errorMessage);
    res['status'] = 'failure';
    res['errormessage'] = errorMessage;
  } else {
    res['status'] = 'ok';
    for (var i = 0; i < successValueArr.length; i++) {
      res[successLabelArr[i]] = successValueArr[i];
    }
  }
  response.send(res);
};

exports.default = {
  isArray: isArray,
  isFileExists: isFileExists,
  isValidPort: isValidPort,
  isValidEmail: isValidEmail,
  isValidName: isValidName,
  isValidDomain: isValidDomain,
  isValidPublicIP: isValidPublicIP,
  checkPortAvailability: checkPortAvailability,
  generateAccessToken: generateAccessToken,
  generateRandomString: generateRandomString,
  convertRelativePathToAbsolute: convertRelativePathToAbsolute,
  generateInstanceId: generateInstanceId,
  getProperty: getProperty,
  onCreate: onCreate,
  onUpdate: onUpdate,
  onFind: onFind,
  onFindOptional: onFindOptional,
  onDelete: onDelete,
  onDeleteOptional: onDeleteOptional,
  sendResponse: sendResponse,
  sendMultipleResponse: sendMultipleResponse
};