using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DotNetDBF;
using Newtonsoft.Json.Linq;

namespace BodyshopPartner.Utils.Decoder
{
    class EstimateDecoder
    {
        public static class CIECAEstimateImport
        {
            private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

            /// <summary>
            /// Decode the set of estimate files based on the creation of an envelope file.
            /// </summary>
            /// <param name="FilePath">Full path to the envelope file that was created/updated.</param>
            /// <returns></returns>
            public static dynamic DecodeEstimate(string FilePath, SourceSystem _source = SourceSystem.Mitchell)
            {
                dynamic ret = new JObject();

                ret.ciecaid = Path.GetFileNameWithoutExtension(FilePath);

                string _dir = Path.GetDirectoryName(FilePath) + @"\";

                ParseAd1File(ref ret, _dir);
                ParseAd2File(ref ret, _dir);
                ParseVehFile(ref ret, _dir);
                ParsePfhFile(ref ret, _dir);
                ParsePflFile(ref ret, _dir, _source);
                ParsePfmFile(ref ret, _dir);
                ParseStlFile(ref ret, _dir);
                ParseTtlFile(ref ret, _dir);
                ParseLinFile(ref ret, _dir);
                ParsePfpFile(ref ret, _dir);
                return ret;
            }

            public static void ParseAd1File(ref dynamic j, string RootFilePath)
            {
                if (string.IsNullOrWhiteSpace(j.ciecaid.Value))
                {
                    return;
                }
                logger.Trace(@"Parsing AD1 at: {0}{1}", RootFilePath, j.ciecaid.Value);

                int retryNumber = 0;
                while (retryNumber < 11)
                {
                    try
                    {
                        using (Stream fis = File.Open(RootFilePath + j.ciecaid.Value + "A.ad1", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            var reader = new DBFReader(fis);

                            reader.SetSelectFields(new string[] { "INS_CO_ID","INS_CO_NM","INS_ADDR1","INS_ADDR2","INS_CITY","INS_ST","INS_ZIP","INS_CTRY",

                                "INS_EA","POLICY_NO","DED_AMT","DED_STATUS","ASGN_NO","ASGN_DATE","ASGN_TYPE","CLM_NO","CLM_OFC_ID","CLM_OFC_NM","CLM_ADDR1",
                                "CLM_ADDR2","CLM_CITY","CLM_ST","CLM_ZIP","CLM_CTRY","CLM_PH1","CLM_PH1X","CLM_PH2","CLM_PH2X","CLM_FAX","CLM_FAXX","CLM_CT_LN",
                                "CLM_CT_FN","CLM_TITLE","CLM_CT_PH","CLM_CT_PHX","CLM_EA","PAYEE_NMS","PAY_TYPE","PAY_DATE","PAY_CHKNM","PAY_AMT","AGT_CO_ID","AGT_CO_NM",
                                "AGT_ADDR1","AGT_ADDR2","AGT_CITY","AGT_ST","AGT_ZIP","AGT_CTRY","AGT_PH1","AGT_PH1X","AGT_PH2","AGT_PH2X","AGT_FAX","AGT_FAXX","AGT_CT_LN",
                                "AGT_CT_FN","AGT_CT_PH","AGT_CT_PHX","AGT_EA","AGT_LIC_NO",
                                "LOSS_DATE","LOSS_TYPE","LOSS_DESC","THEFT_IND","CAT_NO",
                                "TLOS_IND","CUST_PR","INSD_LN","INSD_FN","INSD_TITLE","INSD_CO_NM","INSD_ADDR1","INSD_ADDR2","INSD_CITY","INSD_ST","INSD_ZIP",
                                "INSD_CTRY","INSD_PH1","INSD_PH1X","INSD_PH2","INSD_PH2X","INSD_FAX","INSD_FAXX","INSD_EA","OWNR_LN","OWNR_FN","OWNR_TITLE","OWNR_CO_NM",
                                "OWNR_ADDR1","OWNR_ADDR2","OWNR_CITY","OWNR_ST","OWNR_ZIP","OWNR_CTRY","OWNR_PH1","OWNR_PH1X","OWNR_PH2","OWNR_PH2X","OWNR_FAX","OWNR_FAXX",
                                "OWNR_EA", "INS_PH1","INS_PH1X","INS_PH2","INS_PH2X","INS_FAX","INS_FAXX","INS_CT_LN","INS_CT_FN","INS_TITLE","INS_CT_PH","INS_CT_PHX", "LOSS_CAT",
                            });
                            var readValues = reader.NextRecord();

                            dynamic ownerRoot = new JObject();

                            j.ins_co_id = readValues[0];
                            j.ins_co_nm = readValues[1];
                            j.ins_addr1 = readValues[2];
                            j.ins_addr2 = readValues[3];
                            j.ins_city = readValues[4];
                            j.ins_st = readValues[5];
                            j.ins_zip = readValues[6];
                            j.ins_ctry = readValues[7];
                            j.ins_ea = readValues[8];
                            j.policy_no = readValues[9];
                            j.ded_amt = readValues[10];
                            j.ded_status = readValues[11];
                            j.asgn_no = readValues[12];
                            j.asgn_date = readValues[13];
                            j.asgn_type = readValues[14];
                            j.clm_no = readValues[15];
                            j.clm_ofc_id = readValues[16];
                            j.clm_ofc_nm = readValues[17];
                            j.clm_addr1 = readValues[18];
                            j.clm_addr2 = readValues[19];
                            j.clm_city = readValues[20];
                            j.clm_st = readValues[21];
                            j.clm_zip = readValues[22];
                            j.clm_ctry = readValues[23];
                            j.clm_ph1 = readValues[24];
                            j.clm_ph1x = readValues[25];
                            j.clm_ph2 = readValues[26];
                            j.clm_ph2x = readValues[27];
                            j.clm_fax = readValues[28];
                            j.clm_faxx = readValues[29];
                            j.clm_ct_ln = readValues[30];
                            j.clm_ct_fn = readValues[31];
                            j.clm_title = readValues[32];
                            j.clm_ct_ph = readValues[33];
                            j.clm_ct_phx = readValues[34];
                            j.clm_ea = readValues[35];
                            j.payee_nms = readValues[36];
                            j.pay_type = readValues[37];
                            j.pay_date = readValues[38];
                            j.pay_chknm = readValues[39];
                            j.pay_amt = readValues[40];
                            j.agt_co_id = readValues[41];
                            j.agt_co_nm = readValues[42];
                            j.agt_addr1 = readValues[43];
                            j.agt_addr2 = readValues[44];
                            j.agt_city = readValues[45];
                            j.agt_st = readValues[46];
                            j.agt_zip = readValues[47];
                            j.agt_ctry = readValues[48];
                            j.agt_ph1 = readValues[49];
                            j.agt_ph1x = readValues[50];
                            j.agt_ph2 = readValues[51];
                            j.agt_ph2x = readValues[52];
                            j.agt_fax = readValues[53];
                            j.agt_faxx = readValues[54];
                            j.agt_ct_ln = readValues[55];
                            j.agt_ct_fn = readValues[56];
                            j.agt_ct_ph = readValues[57];
                            j.agt_ct_phx = readValues[58];
                            j.agt_ea = readValues[59];
                            j.agt_lic_no = readValues[60];
                            j.loss_date = readValues[61];
                            j.loss_type = readValues[62];
                            j.loss_desc = readValues[63];
                            j.theft_ind = readValues[64]; //BOOL
                            j.cat_no = readValues[65];
                            j.tlos_ind = readValues[66];
                            j.cust_pr = readValues[67];
                            j.insd_ln = readValues[68];
                            j.insd_fn = readValues[69];
                            j.insd_title = readValues[70];
                            j.insd_co_nm = readValues[71];
                            j.insd_addr1 = readValues[72];
                            j.insd_addr2 = readValues[73];
                            j.insd_city = readValues[74];
                            j.insd_st = readValues[75];
                            j.insd_zip = readValues[76];
                            j.insd_ctry = readValues[77];
                            j.insd_ph1 = readValues[78];
                            j.insd_ph1x = readValues[79];
                            j.insd_ph2 = readValues[80];
                            j.insd_ph2x = readValues[81];
                            j.insd_fax = readValues[82];
                            j.insd_faxx = readValues[83];
                            j.insd_ea = readValues[84];
                            j.ownr_ln = readValues[85];
                            j.ownr_fn = readValues[86];
                            j.ownr_title = readValues[87];
                            j.ownr_co_nm = readValues[88];
                            j.ownr_addr1 = readValues[89];
                            j.ownr_addr2 = readValues[90];
                            j.ownr_city = readValues[91];
                            j.ownr_st = readValues[92];
                            j.ownr_zip = readValues[93];
                            j.ownr_ctry = readValues[94];
                            j.ownr_ph1 = readValues[95];
                            //j.ownr_ph1x = readValues[96];
                            j.ownr_ph2 = readValues[97];
                            // j.ownr_ph2x = readValues[98];
                            //j.ownr_fax = readValues[99];
                            //j.ownr_faxx = readValues[100];
                            j.ownr_ea = readValues[101];
                            j.ins_ph1 = readValues[102];
                            j.ins_ph1x = readValues[103];
                            j.ins_ph2 = readValues[104];
                            j.ins_ph2x = readValues[105];
                            j.ins_fax = readValues[106];
                            j.ins_faxx = readValues[107];
                            j.ins_ct_ln = readValues[108];
                            j.ins_ct_fn = readValues[109];
                            j.ins_title = readValues[110];
                            j.ins_ct_ph = readValues[111];
                            j.ins_ct_phx = readValues[112];
                            j.loss_cat = readValues[113];
                            j.shopid = AppMetaData.ActiveShopId;

                            //Set Owner Record
                            //Owner record will be removed by the application if required. 
                            ownerRoot.ownr_ln = readValues[85];
                            ownerRoot.ownr_fn = readValues[86];
                            ownerRoot.ownr_title = readValues[87];
                            ownerRoot.ownr_co_nm = readValues[88];
                            ownerRoot.ownr_addr1 = readValues[89];
                            ownerRoot.ownr_addr2 = readValues[90];
                            ownerRoot.ownr_city = readValues[91];
                            ownerRoot.ownr_st = readValues[92];
                            ownerRoot.ownr_zip = readValues[93];
                            ownerRoot.ownr_ctry = readValues[94];
                            ownerRoot.ownr_ph1 = readValues[95];
                            ownerRoot.ownr_ph2 = readValues[97];
                            ownerRoot.ownr_ea = readValues[101];
                            ownerRoot.shopid = AppMetaData.ActiveShopId;

                            j.owner = new JObject();
                            j.owner.data = ownerRoot;
                            reader.Dispose();

                            return;
                        }
                    }
                    catch (IOException ex)
                    {
                        logger.Trace(ex, "Unable to open AD1 file. Retrying. ");
                        retryNumber++;
                        Thread.Sleep(3000);
                    }
                }


            }

            public static void ParseAd2File(ref dynamic j, string RootFilePath)
            {
                if (string.IsNullOrWhiteSpace(j.ciecaid.Value))
                {
                    return;
                }
                logger.Trace(@"Parsing AD2 at: {0}{1}", RootFilePath, j.ciecaid.Value);

                int retryNumber = 0;
                while (retryNumber < 11)
                {
                    try
                    {
                        using (Stream fis = File.Open(RootFilePath + j.ciecaid.Value + "B.ad2", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            var reader = new DBFReader(fis);
                            //RO_AUTH references a memo file and had to be reemoved. 
                            reader.SetSelectFields(new string[] { "CLMT_LN","CLMT_FN","CLMT_TITLE","CLMT_CO_NM","CLMT_ADDR1","CLMT_ADDR2","CLMT_CITY","CLMT_ST","CLMT_ZIP","CLMT_CTRY","CLMT_PH1",
"CLMT_PH1X","CLMT_PH2","CLMT_PH2X","CLMT_FAX","CLMT_FAXX","CLMT_EA","EST_CO_ID","EST_CO_NM","EST_ADDR1","EST_ADDR2","EST_CITY","EST_ST","EST_ZIP","EST_CTRY","EST_PH1","EST_PH1X","EST_PH2","EST_PH2X",
"EST_FAX","EST_FAXX","EST_CT_LN","EST_CT_FN","EST_EA","EST_LIC_NO","EST_FILENO","INSP_CT_LN","INSP_CT_FN","INSP_ADDR1","INSP_ADDR2","INSP_CITY","INSP_ST","INSP_ZIP","INSP_CTRY","INSP_PH1","INSP_PH1X",
"INSP_PH2","INSP_PH2X","INSP_FAX","INSP_FAXX","INSP_EA","INSP_CODE","INSP_DESC","INSP_DATE","INSP_TIME","RF_CO_ID","RF_CO_NM","RF_ADDR1","RF_ADDR2","RF_CITY","RF_ST","RF_ZIP","RF_CTRY","RF_PH1","RF_PH1X",
"RF_PH2","RF_PH2X","RF_FAX","RF_FAXX","RF_CT_LN","RF_CT_FN","RF_EA","RF_TAX_ID","RF_LIC_NO","RF_BAR_NO","RO_IN_DATE","RO_IN_TIME",
                                "TAR_DATE","TAR_TIME","RO_CMPDATE","RO_CMPTIME","DATE_OUT","TIME_OUT",
"RF_ESTIMTR","MKTG_TYPE","MKTG_SRC","LOC_NM","LOC_ADDR1","LOC_ADDR2","LOC_CITY","LOC_ST","LOC_ZIP","LOC_CTRY","LOC_PH1","LOC_PH1X","LOC_PH2","LOC_PH2X","LOC_FAX","LOC_FAXX","LOC_CT_LN","LOC_CT_FN","LOC_TITLE",
"LOC_PH","LOC_PHX","LOC_EA"

                            });
                            var readValues = reader.NextRecord();

                            //j.clmt_ln = readValues[0];//CLMT_LN
                            //j.clmt_fn = readValues[1];//CLMT_FN
                            //j.clmt_title = readValues[2];//CLMT_TITLE
                            //j.clmt_co_nm = readValues[3];//CLMT_CO_NM
                            //j.clmt_addr1 = readValues[4];//CLMT_ADDR1
                            //j.clmt_addr2 = readValues[5];//CLMT_ADDR2
                            //j.clmt_city = readValues[6];//CLMT_CITY
                            //j.clmt_st = readValues[7];//CLMT_ST
                            //j.clmt_zip = readValues[8];//CLMT_ZIP
                            //j.clmt_ctry = readValues[9];//CLMT_CTRY
                            //j.clmt_ph1 = readValues[10];//CLMT_PH1
                            //j.clmt_ph1x = readValues[11];//CLMT_PH1X
                            //j.clmt_ph2 = readValues[12];//CLMT_PH2
                            //j.clmt_ph2x = readValues[13];//CLMT_PH2X
                            //j.clmt_fax = readValues[14];//CLMT_FAX
                            //j.clmt_faxx = readValues[15];//CLMT_FAXX
                            //j.clmt_ea = readValues[16];//CLMT_EA
                            //j.est_co_id = readValues[17];//EST_CO_ID
                            j.est_co_nm = readValues[18];//EST_CO_NM
                            j.est_addr1 = readValues[19];//EST_ADDR1
                            j.est_addr2 = readValues[20];//EST_ADDR2
                            j.est_city = readValues[21];//EST_CITY
                            j.est_st = readValues[22];//EST_ST
                            j.est_zip = readValues[23];//EST_ZIP
                            j.est_ctry = readValues[24];//EST_CTRY
                            j.est_ph1 = readValues[25];//EST_PH1
                            //j.est_ph1x = readValues[26];//EST_PH1X
                            //j.est_ph2 = readValues[27];//EST_PH2
                            //j.est_ph2x = readValues[28];//EST_PH2X
                            //j.est_fax = readValues[29];//EST_FAX
                            //j.est_faxx = readValues[30];//EST_FAXX
                            j.est_ct_ln = readValues[31];//EST_CT_LN
                            j.est_ct_fn = readValues[32];//EST_CT_FN
                            j.est_ea = readValues[33];//EST_EA
                            //j.est_lic_no = readValues[34];//EST_LIC_NO
                            //j.est_fileno = readValues[35];//EST_FILENO
                            //j.insp_ct_ln = readValues[36];//INSP_CT_LN
                            //j.insp_ct_fn = readValues[37];//INSP_CT_FN
                            //j.insp_addr1 = readValues[38];//INSP_ADDR1
                            //j.insp_addr2 = readValues[39];//INSP_ADDR2
                            //j.insp_city = readValues[40];//INSP_CITY
                            //j.insp_st = readValues[41];//INSP_ST
                            //j.insp_zip = readValues[42];//INSP_ZIP
                            //j.insp_ctry = readValues[43];//INSP_CTRY
                            //j.insp_ph1 = readValues[44];//INSP_PH1
                            //j.insp_ph1x = readValues[45];//INSP_PH1X
                            //j.insp_ph2 = readValues[46];//INSP_PH2
                            //j.insp_ph2x = readValues[47];//INSP_PH2X
                            //j.insp_fax = readValues[48];//INSP_FAX
                            //j.insp_faxx = readValues[49];//INSP_FAXX
                            //j.insp_ea = readValues[50];//INSP_EA
                            //j.insp_code = readValues[51];//INSP_CODE
                            //j.insp_desc = readValues[52];//INSP_DESC
                            //j.insp_date = readValues[53];//INSP_DATE
                            //j.insp_time = readValues[54];//INSP_TIME
                            //j.rf_co_id = readValues[55];//RF_CO_ID
                            //j.rf_co_nm = readValues[56];//RF_CO_NM
                            //j.rf_addr1 = readValues[57];//RF_ADDR1
                            //j.rf_addr2 = readValues[58];//RF_ADDR2
                            //j.rf_city = readValues[59];//RF_CITY
                            //j.rf_st = readValues[60];//RF_ST
                            //j.rf_zip = readValues[61];//RF_ZIP
                            //j.rf_ctry = readValues[62];//RF_CTRY
                            //j.rf_ph1 = readValues[63];//RF_PH1
                            //j.rf_ph1x = readValues[64];//RF_PH1X
                            //j.rf_ph2 = readValues[65];//RF_PH2
                            //j.rf_ph2x = readValues[66];//RF_PH2X
                            //j.rf_fax = readValues[67];//RF_FAX
                            //j.rf_faxx = readValues[68];//RF_FAXX
                            //j.rf_ct_ln = readValues[69];//RF_CT_LN
                            //j.rf_ct_fn = readValues[70];//RF_CT_FN
                            //j.rf_ea = readValues[71];//RF_EA
                            //j.rf_tax_id = readValues[72];//RF_TAX_ID
                            //j.rf_lic_no = readValues[73];//RF_LIC_NO
                            //j.rf_bar_no = readValues[74];//RF_BAR_NO
                            //j.ro_in_date = readValues[75];//RO_IN_DATE
                            //j.ro_in_time = readValues[76];//RO_IN_TIME
                            //j.tar_date = readValues[77];//TAR_DATE
                            //j.tar_time = readValues[78];//TAR_TIME
                            //j.ro_cmpdate = readValues[79];//RO_CMPDATE
                            //j.ro_cmptime = readValues[80];//RO_CMPTIME
                            //j.date_out = readValues[81];//DATE_OUT
                            //j.time_out = readValues[82];//TIME_OUT
                            //j.rf_estimtr = readValues[83];//RF_ESTIMTR
                            //j.mktg_type = readValues[84];//MKTG_TYPE
                            //j.mktg_src = readValues[85];//MKTG_SRC
                            //j.loc_nm = readValues[86];//LOC_NM
                            //j.loc_addr1 = readValues[87];//LOC_ADDR1
                            //j.loc_addr2 = readValues[88];//LOC_ADDR2
                            //j.loc_city = readValues[89];//LOC_CITY
                            //j.loc_st = readValues[90];//LOC_ST
                            //j.loc_zip = readValues[91];//LOC_ZIP
                            //j.loc_ctry = readValues[92];//LOC_CTRY
                            //j.loc_ph1 = readValues[93];//LOC_PH1
                            //j.loc_ph1x = readValues[94];//LOC_PH1X
                            //j.loc_ph2 = readValues[95];//LOC_PH2
                            //j.loc_ph2x = readValues[96];//LOC_PH2X
                            //j.loc_fax = readValues[97];//LOC_FAX
                            //j.loc_faxx = readValues[98];//LOC_FAXX
                            //j.loc_ct_ln = readValues[99];//LOC_CT_LN
                            //j.loc_ct_fn = readValues[100];//LOC_CT_FN
                            //j.loc_title = readValues[101];//LOC_TITLE
                            //j.loc_ph = readValues[102];//LOC_PH
                            //j.loc_phx = readValues[103];//LOC_PHX
                            //j.loc_ea = readValues[104];//LOC_EA



                            reader.Dispose();
                            return;
                        }
                    }
                    catch (IOException ex)
                    {
                        logger.Trace(ex, "Unable to open AD2 file. Retrying. ");
                        retryNumber++;
                        Thread.Sleep(3000);
                    }
                }


            }

            public static void ParsePfhFile(ref dynamic j, string RootFilePath)
            {
                if (string.IsNullOrWhiteSpace(j.ciecaid.Value))
                {
                    return;
                }
                logger.Trace(@"Parsing PFH at: {0}{1}", RootFilePath, j.ciecaid.Value);

                int retryNumber = 0;
                while (retryNumber < 11)
                {
                    try
                    {
                        using (Stream fis = File.Open(RootFilePath + j.ciecaid.Value + ".pfh", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            var reader = new DBFReader(fis);
                            reader.SetSelectFields(new string[] { "ID_PRO_NAM","TAX_PRETHR","TAX_THRAMT","TAX_PSTTHR","TAX_TOW_IN","TAX_TOW_RT","TAX_STR_IN","TAX_STR_RT","TAX_SUB_IN","TAX_SUB_RT",
                                                                    "TAX_BTR_IN","TAX_LBR_RT","TAX_GST_RT","TAX_GST_IN","ADJ_G_DISC","ADJ_TOWDIS","ADJ_STRDIS","ADJ_BTR_IN","TAX_PREDIS",
                            });
                            var readValues = reader.NextRecord();

                            //Values divided by 100 to make consistent. 

                            //j.id_pro_nam = readValues[0];//ID_PRO_NAM
                            j.tax_prethr = float.Parse(readValues[1].ToString()) / 100;//TAX_PRETHR Parts tax for pre-threshold
                            j.tax_thramt = readValues[2];//TAX_THRAMT Parts threshold amount
                            j.tax_pstthr = float.Parse(readValues[3].ToString()) / 100;//TAX_PSTTHR //PST for Parts
                            //j.tax_tow_in = readValues[4];//TAX_TOW_IN
                            j.tax_tow_rt = (bool)readValues[4] ? float.Parse(readValues[5].ToString()) / 100 : 0;//TAX_TOW_RT

                            //j.tax_str_in = readValues[6];//TAX_STR_IN
                            j.tax_str_rt = (bool)readValues[6] ? float.Parse(readValues[7].ToString()) / 100 : 0;//TAX_STR_RT

                            //j.tax_sub_in = readValues[8];//TAX_SUB_IN
                            j.tax_sub_rt = (bool)readValues[8] ? float.Parse(readValues[9].ToString()) / 100 : 0;//TAX_SUB_RT

                            //j.tax_btr_in = readValues[10];//TAX_BTR_IN
                            j.tax_lbr_rt = float.Parse(readValues[11].ToString()) / 100;//TAX_LBR_RT
                            j.federal_tax_rate = float.Parse(readValues[12].ToString()) / 100;//TAX_GST_RT  //TODO Handling for different tax code fields? 
                            //j.tax_gst_in = readValues[13];//TAX_GST_IN
                            j.adj_g_disc = readValues[14];//ADJ_G_DISC
                            j.adj_towdis = readValues[15];//ADJ_TOWDIS
                            j.adj_strdis = readValues[16];//ADJ_STRDIS

                            //j.adj_btr_in = readValues[17];//ADJ_BTR_IN
                            j.tax_predis = readValues[18];//TAX_PREDIS
                            reader.Dispose();
                            return;
                        }
                    }
                    catch (IOException ex)
                    {
                        logger.Trace(ex, "Unable to open PFH file. Retrying. ");
                        retryNumber++;
                        Thread.Sleep(3000);
                    }
                }
            }

            public static void ParsePflFile(ref dynamic j, string RootFilePath, SourceSystem _source = SourceSystem.Mitchell)
            {
                if (string.IsNullOrWhiteSpace(j.ciecaid.Value))
                {
                    return;
                }
                logger.Trace(@"Parsing PFl at: {0}{1}", RootFilePath, j.ciecaid.Value);

                int retryNumber = 0;
                while (retryNumber < 11)
                {
                    try
                    {
                        using (Stream fis = File.Open(RootFilePath + j.ciecaid.Value + ".pfl", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            var reader = new DBFReader(fis);
                            reader.SetSelectFields(new string[] { "LBR_TYPE",
                                                                    "LBR_DESC",
                                                                    "LBR_RATE",
                                                                    "LBR_TAX_IN",
                                                                    "LBR_TAXP",
                                                                    "LBR_ADJP",
                                                                    "LBR_TX_TY1",
                                                                    "LBR_TX_IN1",
                                                                    "LBR_TX_TY2",
                                                                    "LBR_TX_IN2",
                                                                    "LBR_TX_TY3",
                                                                    "LBR_TX_IN3",
                                                                    "LBR_TX_TY4",
                                                                    "LBR_TX_IN4",
                                                                    "LBR_TX_TY5",
                                                                    "LBR_TX_IN5"
                            });
                            for (int i = 0; i < reader.RecordCount; i++)
                            {
                                var readValues = reader.NextRecord();
                                switch (readValues[0].ToString())//Case switch on LBR_TYPE to assign correctly. 
                                {
                                    case "LAB":
                                        j.rate_lab = readValues[2];
                                        break;
                                    case "LAD":
                                        j.rate_lad = readValues[2];
                                        break;
                                    case "LAS":
                                        j.rate_las = readValues[2];
                                        break;
                                    case "LAR":
                                        j.rate_lar = readValues[2];
                                        break;
                                    case "LAE":
                                        j.rate_lae = readValues[2];
                                        break;
                                    case "LAG":
                                        j.rate_lag = readValues[2];
                                        break;
                                    case "LAF":
                                        j.rate_laf = readValues[2];
                                        break;
                                    case "LAM":
                                        j.rate_lam = readValues[2];
                                        break;
                                    case "LAU":
                                        j.rate_lau = readValues[2];
                                        break;
                                    case "LA1":
                                        if (_source == SourceSystem.Audatex)
                                        { j.rate_laa = readValues[2]; }
                                        else
                                        { j.rate_la1 = readValues[2]; }
                                        break;
                                    case "LA2":
                                        j.rate_la2 = readValues[2];
                                        break;
                                    case "LA3":
                                        if (_source == SourceSystem.Mitchell)
                                        { j.rate_laa = readValues[2]; }
                                        else
                                        { j.rate_la3 = readValues[2]; }
                                        break;
                                    case "LA4":
                                        j.rate_la4 = readValues[2];
                                        break;
                                    default:
                                        logger.Error("Unknown type value present in PFL file. {0}:{1}", readValues[0].ToString(), readValues[2]);
                                        break;
                                }
                            }


                            //j.lbr_type = readValues[0];//LBR_TYPE
                            //j.lbr_desc = readValues[1];//LBR_DESC
                            //j.lbr_rate = readValues[2];//LBR_RATE
                            //j.lbr_tax_in = readValues[3];//LBR_TAX_IN
                            //j.lbr_taxp = readValues[4];//LBR_TAXP
                            //j.lbr_adjp = readValues[5];//LBR_ADJP
                            //j.lbr_tx_ty1 = readValues[6];//LBR_TX_TY1
                            //j.lbr_tx_in1 = readValues[7];//LBR_TX_IN1
                            //j.lbr_tx_ty2 = readValues[8];//LBR_TX_TY2
                            //j.lbr_tx_in2 = readValues[9];//LBR_TX_IN2
                            //j.lbr_tx_ty3 = readValues[10];//LBR_TX_TY3
                            //j.lbr_tx_in3 = readValues[11];//LBR_TX_IN3
                            //j.lbr_tx_ty4 = readValues[12];//LBR_TX_TY4
                            //j.lbr_tx_in4 = readValues[13];//LBR_TX_IN4
                            //j.lbr_tx_ty5 = readValues[14];//LBR_TX_TY5
                            //j.lbr_tx_in5 = readValues[15];//LBR_TX_IN5

                            reader.Dispose();
                            return;
                        }
                    }
                    catch (IOException ex)
                    {
                        logger.Trace(ex, "Unable to open PFl file. Retrying. ");
                        retryNumber++;
                        Thread.Sleep(3000);
                    }
                }
            }

            public static void ParsePfmFile(ref dynamic j, string RootFilePath)
            {
                if (string.IsNullOrWhiteSpace(j.ciecaid.Value))
                {
                    return;
                }
                logger.Trace(@"Parsing PFM at: {0}{1}", RootFilePath, j.ciecaid.Value);

                int retryNumber = 0;
                while (retryNumber < 11)
                {
                    try
                    {
                        using (Stream fis = File.Open(RootFilePath + j.ciecaid.Value + ".pfm", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            //"CAL_LBRMAX may have null values. had to be removed becauase dbf reader expects 0 and not null.
                            var reader = new DBFReader(fis);
                            reader.SetSelectFields(new string[] { "MATL_TYPE",
                                                                "CAL_CODE",
                                                                "CAL_DESC",
                                                                "CAL_MAXDLR",
                                                                "CAL_PRIP",

                                                                "CAL_SECP",
                                                                "MAT_CALP",
                                                                "CAL_PRETHR",
                                                                "CAL_PSTTHR",
                                                                "CAL_THRAMT",

                                                                "CAL_LBRMIN",

                                                                "CAL_LBRRTE",
                                                                "CAL_OPCODE",

                                                                "TAX_IND",
                                                                "MAT_TAXP",
                                                                "MAT_ADJP",
                                                                "MAT_TX_TY1",
                                                                "MAT_TX_IN1",
                                                                "MAT_TX_TY2",
                                                                "MAT_TX_IN2",
                                                                "MAT_TX_TY3",
                                                                "MAT_TX_IN3",
                                                                "MAT_TX_TY4",
                                                                "MAT_TX_IN4",
                                                                "MAT_TX_TY5",
                                                                "MAT_TX_IN5"
                            });
                            for (int i = 0; i < reader.RecordCount; i++)
                            {
                                var readValues = reader.NextRecord();
                                switch (readValues[0].ToString())//Case switch on MATL_TYPE to assign correctly. 
                                {
                                    //TODO: Import MAXDLR for every type. 
                                    case "MAPA":
                                        j.rate_mapa = readValues[7];
                                        j.tax_paint_mat_rt = float.Parse(readValues[14].ToString()) / 100;
                                        break;
                                    case "MASH":
                                        j.rate_mash = readValues[7];
                                        j.tax_shop_mat_rt = float.Parse(readValues[14].ToString()) / 100;

                                        break;
                                    case "MAHW": //TODO Should the remainder of these be index 7 or 11? 
                                        j.rate_mahw = readValues[7];
                                        j.tax_levies_rt = float.Parse(readValues[14].ToString()) / 100;
                                        break;
                                    case "MA2S":
                                        j.rate_ma2s = readValues[7];
                                        break;
                                    case "MA2T":
                                        j.rate_ma2t = readValues[7];
                                        break;
                                    case "MA3S":
                                        j.rate_ma3s = readValues[7];
                                        break;
                                    case "MACS":
                                        j.rate_macs = readValues[7];
                                        break;
                                    case "MABL":
                                        j.rate_mabl = readValues[7];
                                        break;
                                    default:
                                        logger.Error("Unknown type value present in PFM file. {0}:{1}", readValues[0].ToString(), readValues[2]);
                                        break;
                                }
                            }

                            //TODO: There was additional logic in paradox here around the mxdlr being > 0 which it always appears to be.

                            //j.matl_type = readValues[0];//MATL_TYPE
                            //j.cal_code = readValues[1];//CAL_CODE
                            //j.cal_desc = readValues[2];//CAL_DESC
                            //j.cal_maxdlr = readValues[3];//CAL_MAXDLR
                            //j.cal_prip = readValues[4];//CAL_PRIP
                            //j.cal_secp = readValues[5];//CAL_SECP
                            //j.mat_calp = readValues[6];//MAT_CALP
                            //j.cal_prethr = readValues[7];//CAL_PRETHR
                            //j.cal_pstthr = readValues[8];//CAL_PSTTHR
                            //j.cal_thramt = readValues[9];//CAL_THRAMT
                            //j.cal_lbrmin = readValues[10];//CAL_LBRMIN
                            //j.cal_lbrrte = readValues[11];//CAL_LBRRTE
                            //j.cal_opcode = readValues[12];//CAL_OPCODE
                            //j.tax_ind = readValues[13];//TAX_IND
                            //j.mat_taxp = readValues[14];//MAT_TAXP
                            //j.mat_adjp = readValues[15];//MAT_ADJP
                            //j.mat_tx_ty1 = readValues[16];//MAT_TX_TY1
                            //j.mat_tx_in1 = readValues[17];//MAT_TX_IN1
                            //j.mat_tx_ty2 = readValues[18];//MAT_TX_TY2
                            //j.mat_tx_in2 = readValues[19];//MAT_TX_IN2
                            //j.mat_tx_ty3 = readValues[20];//MAT_TX_TY3
                            //j.mat_tx_in3 = readValues[21];//MAT_TX_IN3
                            //j.mat_tx_ty4 = readValues[22];//MAT_TX_TY4
                            //j.mat_tx_in4 = readValues[23];//MAT_TX_IN4
                            //j.mat_tx_ty5 = readValues[24];//MAT_TX_TY5
                            //j.mat_tx_in5 = readValues[25];//MAT_TX_IN5



                            reader.Dispose();
                            return;
                        }
                    }
                    catch (IOException ex)
                    {
                        logger.Trace(ex, "Unable to open PFM file. Retrying. ");
                        retryNumber++;
                        Thread.Sleep(3000);
                    }
                }
            }

            public static void ParseVehFile(ref dynamic j, string RootFilePath)
            {
                if (string.IsNullOrWhiteSpace(j.ciecaid.Value)) { return; }

                logger.Trace(@"Parsing Veh at: {0}{1}", RootFilePath, j.ciecaid.Value);

                int retryNumber = 0;
                while (retryNumber < 11)
                {
                    try
                    {
                        using (Stream fis = File.Open(RootFilePath + j.ciecaid.Value + "v.veh", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            dynamic v = new JObject();
                            //V_Options references a memo file and had to be removed
                            var reader = new DBFReader(fis);
                            reader.SetSelectFields(new string[] { "IMPACT_1",
                                                                "IMPACT_2",
                                                                "DB_V_CODE",
                                                                "PLATE_NO",
                                                                "PLATE_ST",
                                                                "V_VIN",
                                                                "V_COND",
                                                                "V_PROD_DT",
                                                                "V_MODEL_YR",
                                                                "V_MAKECODE",
                                                                "V_MAKEDESC",
                                                                "V_MODEL",
                                                                "V_TYPE",
                                                                "V_BSTYLE",
                                                                "V_TRIMCODE",
                                                                "TRIM_COLOR",
                                                                "V_MLDGCODE",
                                                                "V_ENGINE",

                                                                "V_COLOR",
                                                                "V_TONE",
                                                                "V_STAGE",
                                                                "PAINT_CD1",
                                                                "PAINT_CD2",
                                                                "PAINT_CD3"
                            });

                            var readValues = reader.NextRecord();

                            dynamic d = new JObject();
                            d.impact1 = readValues[0]?.ToString();
                            d.impact2 = readValues[1]?.ToString();

                            j.area_of_damage = d;

                            v.db_v_code = readValues[2]?.ToString();
                            v.plate_no = readValues[3]?.ToString();
                            v.plate_st = readValues[4]?.ToString();
                            v.v_vin = readValues[5]?.ToString();
                            v.v_cond = readValues[6]?.ToString();
                            v.v_prod_dt = readValues[7]?.ToString();
                            v.v_model_yr = readValues[8]?.ToString();
                            v.v_makecode = readValues[9]?.ToString();
                            v.v_make_desc = readValues[10]?.ToString();
                            v.v_model_desc = readValues[11]?.ToString();
                            v.v_type = readValues[12]?.ToString();
                            v.v_bstyle = readValues[13]?.ToString();
                            v.v_trimcode = readValues[14]?.ToString();
                            v.trim_color = readValues[15]?.ToString();
                            v.v_mldgcode = readValues[16]?.ToString();
                            v.v_engine = readValues[17]?.ToString();
                            v.v_color = readValues[18]?.ToString();
                            v.v_tone = readValues[19]?.ToString();
                            v.v_stage = readValues[20]?.ToString();

                            dynamic p = new JObject();
                            p.paint_cd1 = readValues[21]?.ToString();
                            p.paint_cd2 = readValues[22]?.ToString();
                            p.paint_cd3 = readValues[23]?.ToString();
                            v.v_paint_codes = p;

                            j.vehicle = new JObject();
                            j.vehicle.data = v;

                            //Capturing vehicle information on the job as well. 
                            j.plate_no = readValues[3]?.ToString();
                            j.plate_st = readValues[4]?.ToString();
                            j.v_vin = readValues[5]?.ToString();
                            j.v_model_yr = readValues[8]?.ToString();
                            j.v_make_desc = readValues[10]?.ToString();
                            j.v_model_desc = readValues[11]?.ToString();
                            j.v_color = readValues[18]?.ToString();

                            v.shopid = AppMetaData.ActiveShopId;
                        }
                        return;
                    }
                    catch (IOException ex)
                    {
                        logger.Trace(ex, "Unable to open VEH file. Retrying. ");
                        retryNumber++;
                        Thread.Sleep(3000);
                    }
                }
            }

            public static void ParseLinFile(ref dynamic j, string RootFilePath)
            {
                if (string.IsNullOrWhiteSpace(j.ciecaid.Value))
                {
                    return;
                }
                logger.Trace(@"Parsing LIN at: {0}{1}", RootFilePath, j.ciecaid.Value);

                int retryNumber = 0;
                while (retryNumber < 11)
                {
                    try
                    {
                        using (Stream fis = File.Open(RootFilePath + j.ciecaid.Value + ".lin", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            //"CAL_LBRMAX may have null values. had to be removed becauase dbf reader expects 0 and not null.
                            var reader = new DBFReader(fis);
                            reader.SetSelectFields(new string[] { "LINE_NO",
                                                                    "LINE_IND",
                                                                    "LINE_REF",
                                                                    "TRAN_CODE",
                                                                    "DB_REF",
                                                                    "UNQ_SEQ",
                                                                    "WHO_PAYS",
                                                                    "LINE_DESC",
                                                                    "PART_TYPE",
                                                                    "PART_DESCJ",
                                                                    "GLASS_FLAG",
                                                                    "OEM_PARTNO",
                                                                    "PRICE_INC",
                                                                    "ALT_PART_I",
                                                                    "TAX_PART",
                                                                    "DB_PRICE",
                                                                    "ACT_PRICE",
                                                                    "PRICE_J",
                                                                    "CERT_PART",
                                                                    "PART_QTY",
                                                                    "ALT_CO_ID",
                                                                    "ALT_PARTNO",
                                                                    "ALT_OVERRD",
                                                                    "ALT_PARTM",
                                                                    "PRT_DSMK_P",
                                                                    "PRT_DSMK_M",
                                                                    "MOD_LBR_TY",
                                                                    "DB_HRS",
                                                                    "MOD_LB_HRS",
                                                                    "LBR_INC",
                                                                    "LBR_OP",
                                                                    "LBR_HRS_J",
                                                                    "LBR_TYP_J",
                                                                    "LBR_OP_J",
                                                                    "PAINT_STG",
                                                                    "PAINT_TONE",
                                                                    "LBR_TAX",
                                                                    "LBR_AMT",
                                                                    "MISC_AMT",
                                                                    "MISC_SUBLT",
                                                                    "MISC_TAX",
                                                                    "BETT_TYPE",
                                                                    "BETT_PCTG",
                                                                    "BETT_AMT",
                                                                    "BETT_TAX",

                            });

                            var allLines = new JArray();



                            #region Code
                            //TODO: How to handle price markup and discounts. 
                            //                      if Number(tcLin."PRT_DSMK_P") = 0 then

                            //          switch

                            //              case TblEstimatingPlatform= "Audatex": ; calculate adjustmetn without the amount in tcMitchell."PRT_DSMK_M

                            //                  StrPercentAdj = Number(tcLin."PRT_DSMK_P")

                            //                  StrActPrice = (Number(tcLin."PART_QTY") * Number(tcLin."ACT_PRICE")) * (1 + (StrPercentAdj / 100)); '----------------------------  PRT_DSMK_M

                            //                  tcEstLine."ACT_PRICE" = StrActPrice

                            //                  tcEstLine."MISC_AMT" = tcLin."MISC_AMT"

                            //              case TblEstimatingPlatform= "CCC" :
                            //if tcLin."MOD_LBR_TY" = "LAR" then

                            //                      tcEstLine."ACT_PRICE" = ""; Price has to be blank,CCC puts the part price on body and refinish lines doubling the price

                            //                  else
                            //                              tcEstLine."ACT_PRICE" = Number(tcLin."PART_QTY") * Number(tcLin."ACT_PRICE")

                            //                  endif

                            //                  if Number(tcLin."MISC_AMT") > 0 then; some sublet operations are posted to tcLin."MISC_AMT"

                            //                      tcEstLine."ACT_PRICE" = tcLin."MISC_AMT"

                            //                  endif
                            //              otherwise:
                            //tcEstLine."ACT_PRICE" = Number(tcLin."PART_QTY") * Number(tcLin."ACT_PRICE")

                            //                  tcEstLine."MISC_AMT" = tcLin."MISC_AMT"

                            //          endswitch

                            //      else
                            //          if TblEstimatingPlatform = "Audatex" then; calculate adjustmetn without the amount in tcMitchell."PRT_DSMK_M

                            //              tcEstLine."ACT_PRICE" = (Number(tcLin."PART_QTY") * Number(tcLin."ACT_PRICE")) * (1 + (Number(tcLin."PRT_DSMK_P") / 100)); '----------------------------  PRT_DSMK_M

                            //          else
                            //                              tcEstLine."ACT_PRICE" = (Number(tcLin."PART_QTY") * Number(tcLin."ACT_PRICE")) + Number(tcLin."PRT_DSMK_M")

                            //          endif
                            //      endif
                            #endregion




                            for (int i = 0; i < reader.RecordCount; i++)
                            {

                                var readValues = reader.NextRecord();
                                dynamic lin = new JObject();

                                //Mising est_seq
                               
                                lin.line_no = readValues[0];//LINE_NO
                                lin.line_ind = readValues[1];//LINE_IND
                                lin.line_ref = readValues[2];//LINE_REF
                                //lin.tran_code = readValues[3];//TRAN_CODE
                                lin.db_ref = readValues[4];//DB_REF
                                lin.unq_seq = readValues[5];//UNQ_SEQ
                                //lin.who_pays = readValues[6];//WHO_PAYS
                                lin.line_desc = readValues[7];//LINE_DESC
                                lin.part_type = readValues[8];//PART_TYPE
                                //lin.part_descj = readValues[9];//PART_DESCJ
                                lin.glass_flag = readValues[10];//GLASS_FLAG
                                lin.oem_partno = readValues[11];//OEM_PARTNO
                                lin.price_inc = readValues[12];//PRICE_INC
                                lin.alt_part_i = readValues[13];//ALT_PART_I
                                lin.tax_part = readValues[14];//TAX_PART
                                lin.db_price = readValues[15];//DB_PRICE
                                lin.act_price = readValues[16];//ACT_PRICE
                                lin.price_j = readValues[17];//PRICE_J
                                lin.cert_part = readValues[18];//CERT_PART
                                lin.part_qty = readValues[19];//PART_QTY
                                lin.alt_co_id = readValues[20];//ALT_CO_ID
                                lin.alt_partno = readValues[21];//ALT_PARTNO
                                lin.alt_overrd = readValues[22];//ALT_OVERRD
                                lin.alt_partm = readValues[23];//ALT_PARTM
                                lin.prt_dsmk_p = readValues[24];//PRT_DSMK_P
                                lin.prt_dsmk_m = readValues[25];//PRT_DSMK_M
                                lin.mod_lbr_ty = readValues[26];//MOD_LBR_TY



                                lin.db_hrs = readValues[27];//DB_HRS
                                lin.mod_lb_hrs = readValues[28];//MOD_LB_HRS
                                lin.lbr_inc = readValues[29];//LBR_INC
                                lin.lbr_op = readValues[30];//LBR_OP

                                lin.lbr_hrs_j = readValues[31];//LBR_HRS_J
                                lin.lbr_typ_j = readValues[32];//LBR_TYP_J
                                lin.lbr_op_j = readValues[33];//LBR_OP_J
                                lin.paint_stg = readValues[34];//PAINT_STG
                                lin.paint_tone = readValues[35];//PAINT_TONE
                                lin.lbr_tax = readValues[36];//LBR_TAX
                                lin.lbr_amt = readValues[37];//LBR_AMT
                                lin.misc_amt = readValues[38];//MISC_AMT
                                lin.misc_sublt = readValues[39];//MISC_SUBLT
                                lin.misc_tax = readValues[40];//MISC_TAX
                                lin.bett_type = readValues[41];//BETT_TYPE
                                lin.bett_pctg = readValues[42];//BETT_PCTG
                                lin.bett_amt = readValues[43];//BETT_AMT
                                lin.bett_tax = readValues[44];//BETT_TAX

                                //Create new column to capture lbr op code description. in UI, show partno ? partno : op code desc. has to be stamped
                                //If the OEM_PARTNO is empty, use the operation code and look it up in opcode table. If found, take opcode.opcodedescription and populate oem_partno with it
                                //populate lbr_op with opcode.opcodetouse
                                //if part_type is blank, pull in the part type from parttypetousemitchell
                                //if not found, set description to not efined

                                if (string.IsNullOrEmpty(lin.oem_partno.Value))
                                {
                                    try
                                    {
                                        lin.op_code_desc = Utils.AppMetaData.CiecaOpCodes[lin.lbr_op.Value]["desc"].Value;
                                    }
                                    catch (Exception Ex)
                                    {
                                        logger.Warn(Ex, "Couldnt find OpCodeDesc from {0} ", lin.lbr_op.Value);
                                    }

                                }


                                allLines.Add(lin);
                            }

                            j.joblines = new JObject();
                            j.joblines.data = allLines;


                            reader.Dispose();
                            return;
                        }
                    }
                    catch (IOException ex)
                    {
                        logger.Trace(ex, "Unable to open LIN file. Retrying. ");
                        retryNumber++;
                        Thread.Sleep(3000);
                    }
                }
            }

            public static void ParseTtlFile(ref dynamic j, string RootFilePath)
            {
                if (string.IsNullOrWhiteSpace(j.ciecaid.Value)) { return; }

                logger.Trace(@"Parsing Ttl at: {0}{1}", RootFilePath, j.ciecaid.Value);

                int retryNumber = 0;
                while (retryNumber < 11)
                {
                    try
                    {
                        using (Stream fis = File.Open(RootFilePath + j.ciecaid.Value + ".ttl", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            var reader = new DBFReader(fis);
                            reader.SetSelectFields(new string[] { "G_TTL_AMT","G_BETT_AMT","G_RPD_AMT","G_DED_AMT","G_CUST_AMT","G_AA_AMT","N_TTL_AMT","PREV_NET",
                                "SUPP_AMT","N_SUPP_AMT","G_UPD_AMT","G_TTL_DISC","G_TAX","GST_AMT", });
                            var readValues = reader.NextRecord();

                            dynamic ttl_x = new JObject();
                            ttl_x.g_ttl_amt = readValues[0];//G_TTL_AMT
                            ttl_x.g_bett_amt = readValues[1];//G_BETT_AMT
                            ttl_x.g_rpd_amt = readValues[2];//G_RPD_AMT
                            ttl_x.g_ded_amt = readValues[3];//G_DED_AMT
                            ttl_x.g_cust_amt = readValues[4];//G_CUST_AMT
                            ttl_x.g_aa_amt = readValues[5];//G_AA_AMT
                            ttl_x.n_ttl_amt = readValues[6];//N_TTL_AMT
                            ttl_x.prev_net = readValues[7];//PREV_NET
                            ttl_x.supp_amt = readValues[8];//SUPP_AMT
                            ttl_x.n_supp_amt = readValues[9];//N_SUPP_AMT
                            ttl_x.g_upd_amt = readValues[10];//G_UPD_AMT
                            ttl_x.g_ttl_disc = readValues[11];//G_TTL_DISC
                            ttl_x.g_tax = readValues[12];//G_TAX
                            ttl_x.gst_amt = readValues[13];//GST_AMT

                            j.clm_total = Convert.ToDecimal(readValues[0].ToString());

                            j.cieca_ttl = new JObject();
                            j.cieca_ttl.data = ttl_x;


                        }
                        return;
                    }
                    catch (IOException ex)
                    {
                        logger.Trace(ex, "Unable to open TTL file. Retrying. ");
                        retryNumber++;
                        Thread.Sleep(3000);
                    }
                }
            }

            public static void ParseStlFile(ref dynamic j, string RootFilePath)
            {
                if (string.IsNullOrWhiteSpace(j.ciecaid.Value)) { return; }

                logger.Trace(@"Parsing STL at: {0}{1}", RootFilePath, j.ciecaid.Value);

                int retryNumber = 0;
                while (retryNumber < 11)
                {
                    try
                    {
                        using (Stream fis = File.Open(RootFilePath + j.ciecaid.Value + ".stl", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            var reader = new DBFReader(fis);
                            reader.SetSelectFields(new string[] { "TTL_TYPE","TTL_TYPECD","T_AMT","T_HRS","T_ADDLBR","T_DISCAMT","T_MKUPAMT","T_GDISCAMT",
                                                "TAX_AMT","NT_AMT","NT_HRS","NT_ADDLBR","NT_DISC","NT_MKUP","NT_GDIS","TTL_TYPAMT","TTL_HRS","TTL_AMT",
                                                                        });
                            var _rc = reader.RecordCount;
                            var totals = new JArray();
                            for (var i = 0; i < _rc; i++)
                            {
                                var readValues = reader.NextRecord();
                                dynamic ttl_x = new JObject();

                                ttl_x.ttl_type = readValues[0];//TTL_TYPE
                                ttl_x.ttl_typecd = readValues[1];//TTL_TYPECD
                                ttl_x.t_amt = readValues[2];//T_AMT
                                ttl_x.t_hrs = readValues[3];//T_HRS
                                //ttl_x.t_addlbr = readValues[4];//T_ADDLBR
                                //ttl_x.t_discamt = readValues[5];//T_DISCAMT
                                //ttl_x.t_mkupamt = readValues[6];//T_MKUPAMT
                                //ttl_x.t_gdiscamt = readValues[7];//T_GDISCAMT
                                ttl_x.tax_amt = readValues[8];//TAX_AMT
                                //ttl_x.nt_amt = readValues[9];//NT_AMT
                                //ttl_x.nt_hrs = readValues[10];//NT_HRS
                                //ttl_x.nt_addlbr = readValues[11];//NT_ADDLBR
                                //ttl_x.nt_disc = readValues[12];//NT_DISC
                                //ttl_x.nt_mkup = readValues[13];//NT_MKUP
                                //ttl_x.nt_gdis = readValues[14];//NT_GDIS
                                //ttl_x.ttl_typamt = readValues[15];//TTL_TYPAMT
                                ttl_x.ttl_hrs = readValues[16];//TTL_HRS
                                ttl_x.ttl_amt = readValues[17];//TTL_AMT


                                totals.Add(ttl_x);
                            }

                            j.cieca_stl = new JObject();
                            j.cieca_stl.data = totals;
                        }
                        return;
                    }
                    catch (IOException ex)
                    {
                        logger.Trace(ex, "Unable to open STL file. Retrying. ");
                        retryNumber++;
                        Thread.Sleep(3000);
                    }
                }
            }

            public static void ParsePfpFile(ref dynamic j, string RootFilePath)
            {
                if (string.IsNullOrWhiteSpace(j.ciecaid.Value))
                {
                    return;
                }
                logger.Trace(@"Parsing PFP at: {0}{1}", RootFilePath, j.ciecaid.Value);

                int retryNumber = 0;
                while (retryNumber < 11)
                {
                    try
                    {
                        using (Stream fis = File.Open(RootFilePath + j.ciecaid.Value + ".pfp", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            //"CAL_LBRMAX may have null values. had to be removed becauase dbf reader expects 0 and not null.
                            var reader = new DBFReader(fis);
                            reader.SetSelectFields(new string[] { "PRT_TYPE",
                                                                "PRT_TAX_IN",
                                                                "PRT_TAX_RT",
                                                                "PRT_MKUPP",
                                                                "PRT_MKTYP",
                                                                "PRT_DISCP",
                                                                "PRT_TX_TY1",
                                                                "PRT_TX_IN1",
                                                                "PRT_TX_TY2",
                                                                "PRT_TX_IN2",
                                                                "PRT_TX_TY3",
                                                                "PRT_TX_IN3",
                                                                "PRT_TX_TY4",
                                                                "PRT_TX_IN4",
                                                                "PRT_TX_TY5",
                                                                "PRT_TX_IN5"                            });

                            var taxRates = new JObject();


                            for (int i = 0; i < reader.RecordCount; i++)
                            {
                                var readValues = reader.NextRecord();
                                dynamic t = new JObject();

                                t.prt_type = readValues[0];//PRT_TYPE
                                t.prt_tax_in = readValues[1];//PRT_TAX_IN
                                t.prt_tax_rt = (bool)readValues[1] ? float.Parse(readValues[2].ToString()) / 100 : 0;//PRT_TAX_RT  
                                t.prt_mkupp = readValues[3];//PRT_MKUPP
                                t.prt_mktyp = readValues[4];//PRT_MKTYP
                                t.prt_discp = readValues[5];//PRT_DISCP
                                //t.prt_tx_ty1 = readValues[6];//PRT_TX_TY1
                                //t.prt_tx_in1 = readValues[7];//PRT_TX_IN1
                                //t.prt_tx_ty2 = readValues[8];//PRT_TX_TY2
                                //t.prt_tx_in2 = readValues[9];//PRT_TX_IN2
                                //t.prt_tx_ty3 = readValues[10];//PRT_TX_TY3
                                //t.prt_tx_in3 = readValues[11];//PRT_TX_IN3
                                //t.prt_tx_ty4 = readValues[12];//PRT_TX_TY4
                                //t.prt_tx_in4 = readValues[13];//PRT_TX_IN4
                                //t.prt_tx_ty5 = readValues[14];//PRT_TX_TY5
                                //t.prt_tx_in5 = readValues[15];//PRT_TX_IN5

                                taxRates[readValues[0]] = t;
                            }
                            j.parts_tax_rates = taxRates;

                            reader.Dispose();
                            return;
                        }
                    }
                    catch (IOException ex)
                    {
                        logger.Trace(ex, "Unable to open LIN file. Retrying. ");
                        retryNumber++;
                        Thread.Sleep(3000);
                    }
                }
            }


        }
    }
}
