"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.setTestInfoStatus = exports.jsonHelper = exports.jsonConcate = exports.getRunnerDetail = exports.fileHandler = void 0;

let fs = require('fs');

let os = require('os');

let {
  getCurrentBranch
} = require('./');

let getRunnerDetail = () => {
  let defaultObj = {
    jobDetails: {
      isRunByLocal: true,
      hostName: os.hostname(),
      platForm: os.type(),
      branchName: getCurrentBranch('git', process.cwd())
    }
  };
  return defaultObj;
};

exports.getRunnerDetail = getRunnerDetail;
let fileHandler = {
  readFile: (path, callback = null) => {
    if (fs.existsSync(path)) {
      if (callback === null) {
        return fs.readFileSync(path);
      }

      callback(fs.readFileSync(path));
    } else {
      return fileHandler.writeFile(path, getRunnerDetail());
    }
  },
  writeFile: (path, data) => {
    fs.writeFileSync(path, JSON.stringify(data));
    return JSON.stringify(data);
  }
};
exports.fileHandler = fileHandler;

const isObject = obj => obj && obj.constructor === {}.constructor;

const isArray = obj => obj && obj.constructor === [].constructor; // In below funtion 
//  this function is for concat two json  object like _.extend, 
//  if botha array we  concat them 
//  if  both object we use call this  function  recurcively
//  if both differend data type we will just  assign it  


let jsonConcate = (receiverObj, senterObj) => {
  Object.keys(senterObj).map(key => {
    if (Object.prototype.hasOwnProperty.call(receiverObj, key)) {
      if (isObject(receiverObj[key]) && isObject(senterObj[key])) {
        jsonConcate(receiverObj[key], senterObj[key]);
      } else if (isArray(receiverObj[key]) && isArray(senterObj[key])) {
        receiverObj[key] = receiverObj[key].concat(senterObj[key]);
      } else {
        receiverObj[key] = senterObj[key];
      }
    } else {
      receiverObj[key] = senterObj[key];
    }

    return key;
  });
  return receiverObj;
};

exports.jsonConcate = jsonConcate;

let jsonHelper = (path, pathArray, value) => {
  let tempObj = {};

  if (typeof pathArray === 'string') {
    pathArray = pathArray.split('.'); //eslint-disable-line no-param-reassign
  }

  pathArray.slice(0).reverse().map(key => {
    tempObj = {};
    tempObj[key] = value;
    value = tempObj; // eslint-disable-line no-param-reassign

    return key;
  });
  let overAllObj = jsonConcate(JSON.parse(fileHandler.readFile(path)), tempObj);
  fileHandler.writeFile(path, overAllObj);
};

exports.jsonHelper = jsonHelper;

let setTestInfoStatus = (filepath, status) => {
  let buildObject = JSON.parse(fileHandler.readFile(filepath));

  if (!buildObject.testInfo || buildObject.testInfo.isBuildVerified !== false) {
    jsonHelper(filepath, 'testInfo.isBuildVerified', status);
  }
};

exports.setTestInfoStatus = setTestInfoStatus;