var fs = require('fs');
var path = require('path');
var rpm = require("./pid/01_0C_rpm")
var speed = require("./pid/01_0D_vss")
var throttlepos = require("./pid/01_11_throttlepos")
var transactualgear = require("./pid/01_A1_transactualgear")

const pIDList = {};

const loadPidList = () => {
  console.log("Loading list");

  pIDList[`${rpm.mode}-${rpm.pid}`] = rpm;
  pIDList[`${speed.mode}-${speed.pid}`] = speed;
  pIDList[`${throttlepos.mode}-${throttlepos.pid}`] = throttlepos;
  pIDList[`${transactualgear.mode}-${transactualgear.pid}`] = transactualgear;

  // let basePath = path.join(__dirname, ".", "pid");
  // try {
  //     if (fs.statSync(basePath)) {
  //         fs.readdirSync(basePath).forEach(function (file) {
  //             var tmpPidObject = require(path.join(basePath, file));
  //             pIDList[`${tmpPidObject.mode}-${tmpPidObject.pid}`] = tmpPidObject;
  //         });
  //     }
  // }
  // catch (e) {
  //   console.log(e)
  //   console.log("[ERROR] Data directory not found!");
  // }
  console.log("Loaded count: " + Object.keys(pIDList).length);
};

const dec2hex = (decNumber) => {
  var hexNumber;
  if (decNumber < 0) {
      decNumber = 0xFFFFFFFF + decNumber + 1;
  }
  hexNumber = String(decNumber.toString(16).toUpperCase());
  if (hexNumber.length === 1) {
      hexNumber = "0" + hexNumber;
  }
  return hexNumber;
};

const hex2dec = (hexNumber) => {
  return parseInt(hexNumber, 16);
};

const getByPid = (pid, mode) => {
  mode = !mode ? "01" : mode;
  pid = !pid ? "" : pid;
  return pIDList[`${mode}-${pid}`]
};

const parse = (hexString) => {
  let reply = {
      value: undefined,
      name: undefined,
      mode: undefined,
      pid: undefined,
      min: undefined,
      max: undefined,
      unit: undefined,
    },
    byteNumber,
    valueArray; //New object

  // No data or OK is the response.
  if (hexString === 'NO DATA' || hexString === 'OK' || hexString === '?') {
    reply.value = hexString;
    return reply;
  }

  valueArray = [];
  valueArray = hexString.split("|");
  // PID mode
  if (valueArray[2] === '41') {
    reply.mode = valueArray[2];
    reply.pid = valueArray[3];

    const pidObj = getByPid(reply.pid);
    
    let numberOfBytes = pidObj.bytes;

    reply.name = pidObj.name;
    reply.min = pidObj.min;
    reply.max = pidObj.max;
    reply.unit = pidObj.unit;

    // Use static parameter (performance up, usually)
    switch (numberOfBytes) {
      case 1:
        reply.value = pidObj.convertToUseful(valueArray[4]);
        break;

      case 2:
        reply.value = pidObj.convertToUseful(valueArray[4], valueArray[5]);
        break;

      case 4:
        reply.value = pidObj.convertToUseful(
          valueArray[4],
          valueArray[5],
          valueArray[6],
          valueArray[7]
        );
        break;

      case 8:
        reply.value = pidObj.convertToUseful(
          valueArray[4],
          valueArray[5],
          valueArray[6],
          valueArray[7],
          valueArray[8],
          valueArray[9],
          valueArray[10],
          valueArray[11]
        );
        break;

      // Special length, dynamic parameters
      default:
        reply.value = pidObj.convertToUseful.apply(
          this,
          valueArray.slice(2, 2 + parseInt(numberOfBytes, 10))
        );    }  
  }

  // DTC mode
  else if (valueArray[0] === '43') {
    reply.mode = valueArray[0];
    for (let i = 0; i < this._pidList.length; i++) {
      if (this._pidList[i].mode === '03') {
        reply.name = this._pidList[i].name;
        reply.value = this._pidList[i].convertToUseful(
          valueArray[1],
          valueArray[2],
          valueArray[3],
          valueArray[4],
          valueArray[5],
          valueArray[6]
        );
      }
    }
  }

  return reply;
};

loadPidList();
module.exports = { parse, getByPid, dec2hex, hex2dec };
