var _db = require("topsin.database");
var _error = require("topsin.error");
var _ = require("lodash");
var os = require("os");

try {
  var erp_conn_param = {
    database_type: "mssql",
    database_host: "10.3.1.250",
    database_name: "UniTech3",
    database_user: "TopLinker",
    database_pwd: "837914",
    auto_close_timeout: -1
  };
  if (os.type() == "linux") {
    erp_conn_param.database_host = "10.3.1.250\\MSSQLSERVER";
    erp_conn_param.database_driver = "/usr/local/freetds/lib/libtdsodbc.so.0";
  }
  var ERP_CONN_NAME = 'ERP_CONN_NAME';

  var dist_conn_param = {
    database_type: "pg",
    database_host: "139.196.104.13:5433",
    database_name: "TOPDFM_DEV_V6",
    database_user: "toplinker",
    database_pwd: "TopLinker0510",
    auto_close_timeout: -1
  };
  var DIST_CONN_NAME = 'DIST_CONN_NAME';

  _db.addConnection(erp_conn_param, ERP_CONN_NAME);
  var query_erp = _db.query(ERP_CONN_NAME);

  _db.addConnection(dist_conn_param, DIST_CONN_NAME);
  var query_dist = _db.query(DIST_CONN_NAME);

  // query from erp database
  var sql = " \
  SELECT top 1 * \
  FROM dbo.MTL_DemenseDtl \
  WHERE PaperNo = 'BL118040001' AND Item = '7' \
  ";
  var erp_data = query_erp.selectMap(sql, {});
  if (query_erp.lastError().isValid()) {
    throw query_erp.lastError().text();
  }
  print("query result: ", JSON.stringify(erp_data));

  erp_data = _.mapValues(erp_data, function(v, k){
    return _.isString(v) ? v.replace(/\u0000/g, '') : v;
  });

  print("after mapValues: ", JSON.stringify(erp_data));

  // insert to dist database
  query_dist.insertRow({
    table: "tmp_20200106",
    data: erp_data,
    field: ['PaperNo', 'Item', 'StockId', 'MatCode', 'MatName', 'MatGauge', 'Notes']
  });
  if (query_dist.lastError().isValid()) {
    throw query_dist.lastError().text();
  }
} catch (e) {
  print(e);
}