const csvToJson = require('csvtojson');
const { Parser } = require('json2csv');
const fs = require('fs');

function formatPhoneNumber(phoneNumber){
  return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(2, 3)}-${phoneNumber.slice(5)}`;
}

function processFiles(){
  csvToJson({
    noheader: false,
    headers: [
      'PropertyAddress',
      'PropertyName',
      'RBA',
      'City',
      'State',
      'Zip',
      'CountyName',
      'LandAreaAC',
      'ParcelNumber1',
      'PropertyType',
      'TrueOwnerAddress',
      'TrueOwnerCityStateZip',
      'TrueOwnerContact',
      'TrueOwnerName',
      'TrueOwnerPhone',
      'SecondaryType',
      'OwnerName',
      'OwnerPhone'
    ]
  }).fromFile('./data/i96.csv').then((jsonObj) => {
    let data = jsonObj.map((x) => {
      let y = {};
      y['Description Address L Name'] = `"${x.PropertyAddress} ${x.City} ${x.State} ${x.Zip.slice(0, 5)}"`;
      y['Property Address L Custom Building Address'] = `${x.PropertyAddress} ${x.City} ${x.State} ${x.Zip.slice(0, 5)}`;
      y['Property Name L Custom Property Name'] = x.PropertyName;
      y['RBA L Custom SF Building'] = x.RBA;
      y['Property Address P'] = x.PropertyAddress;
      y['City P'] = x.City;
      y['State P'] = x.State;
      y['No Zip'] = x.Zip;
      y['Zip P'] = x.Zip.slice(0, 5);
      y['County Name C Territory'] = x.CountyName;
      y['Land Area (AC) L Custom'] = x.LandAreaAC;
      y['Parcel Number L Custom'] = x.ParcelNumber1;
      y['Property Type L Tag'] = 'Industrial';
      y['True Owner Address C Address: Main Address 1 Full Adress'] = x.TrueOwnerAddress;
      y['True Owner City State Zip C Address: Main City'] = x.TrueOwnerCityStateZip;
      y['True Owner Contact P Full Name'] = x.TrueOwnerContact;
      y['True Owner Name L Custom True Owner'] = x.TrueOwnerName;
      y['True Owner Phone P Work'] = formatPhoneNumber(x.TrueOwnerPhone);
      y['Secondary Type L Custom'] =  x.SecondaryType;
      y['Owner Name L Custom Owners Name'] = '';
      y['Owner Phone L owner Phone'] = '';
      y['Owner Name Name C Name'] = x.TrueOwnerName;
      y['Assignee L Assignee'] = 'EJR';
      y['C Tag Industrial'] = 'Industrial';
      y['Market Area L Custom'] = 'Central I-96 Corridor';
      y['Owner C Tag'] = 'Owner';
      y['Status L'] = 'Pending';
      y['C Description'] = 'Owner';

      return y;
    });
    fs.writeFileSync('./data/result.txt', JSON.stringify(data));
    const parser = new Parser({
      quote: '',
    });
    const csv = parser.parse(data);
    // console.log(csv);
    fs.writeFileSync('./data/result.csv', csv);
  });
}

processFiles();
