// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2018 Thomas Klose & Torsten Schache, Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.


using System;
using System.Collections.Generic;
using System.IO;

using Hiperscan.Spectroscopy.IO;
using Hiperscan.Unix;


namespace Hiperscan.ApoIdentCommon.ApoConfig.ThirdPartyDataExchange
{
    public class DataExchangeLennartz : DataExchange
    {
        private enum ReportExchangeDataColumns
        {
            Key,
            PrimarySubstanceName,
            HiperScanSubstanceId,
            Producer,
            BatchNumber,
            TypeOfDate,
            ExpiryDate,
            PZN,
            User,
            HiperScanProtocolPdf,
            WeightCorrFactor,
        }

        public DataExchangeLennartz()
        {
        }

        protected override DateTime? ConvertToExpiryDate(string date)
        {
            try
            {

                string[] tmp = date.Split(new char[] { '.' });
                int day = Int32.Parse(tmp[0]);
                int month = Int32.Parse(tmp[1]);
                int year = Int32.Parse(tmp[2]);

                return new DateTime(year, month, day);
            }
            catch(Exception)
            {
                return null;
            }

        }

        protected override void DeleteImportFile() => FileIO.DeleteFile(Path.Combine(this.WorkingDir, this.CurrentDataSetKey), true);

        public override void ExportFile(string protocol_pdf_file)
        {
            string file = this.CurrentDataSetKey.Replace(this.DefaultImportFileExtension, this.DefaultExportFileExtension);
            file = Path.Combine(this.WorkingDir, file);      

            Dictionary<int, List<string>> csv_data = new Dictionary<int, List<string>>();
            csv_data.Add(1, new List<string>());
 
            this[this.CurrentDataSetKey].HiperScanProtocolPdf = protocol_pdf_file;

            csv_data[1].Add(this[this.CurrentDataSetKey].ThirdPartyKey);
            csv_data[1].Add(this[this.CurrentDataSetKey].PrimarySubstanceName);
            csv_data[1].Add(this[this.CurrentDataSetKey].HiperScanSubstanceId);
            csv_data[1].Add(this[this.CurrentDataSetKey].Producer);
            csv_data[1].Add(this[this.CurrentDataSetKey].BatchNumber);
            csv_data[1].Add(this[this.CurrentDataSetKey].TypeOfDate);
            csv_data[1].Add(this[this.CurrentDataSetKey].ExpiryDate?.ToString("dd.MM.yyyy") ?? String.Empty);
            csv_data[1].Add(this[this.CurrentDataSetKey].Ppn);
            csv_data[1].Add(this[this.CurrentDataSetKey].User);
            csv_data[1].Add(this[this.CurrentDataSetKey].HiperScanProtocolPdf);

            if (this[this.CurrentDataSetKey].HasWeightCorrFactor)
                csv_data[1].Add(this[this.CurrentDataSetKey].WeightCorrFactor);

            PlainCSV.Write(csv_data, file);
            this.DeleteImportFile();
        }

        public override void ImportFiles()
        {
            this.Clear();
            string pattern = "*" + this.DefaultImportFileExtension;

            foreach (string file in FileIO.GetFiles(this.WorkingDir, pattern))
            {
                try
                {
                    Dictionary<int, List<string>> csv_data = PlainCSV.Read(file);

                    ExchangeDataSet data_set = new ExchangeDataSet();

                    data_set.ThirdPartyKey = csv_data[1][(int)ReportExchangeDataColumns.Key];
                    data_set.PrimarySubstanceName = csv_data[1][(int)ReportExchangeDataColumns.PrimarySubstanceName];
                    data_set.HiperScanSubstanceId = csv_data[1][(int)ReportExchangeDataColumns.HiperScanSubstanceId];
                    data_set.Producer = csv_data[1][(int)ReportExchangeDataColumns.Producer];
                    data_set.BatchNumber = csv_data[1][(int)ReportExchangeDataColumns.BatchNumber];
                    data_set.TypeOfDate = csv_data[1][(int)ReportExchangeDataColumns.TypeOfDate];
                    data_set.ExpiryDate = this.ConvertToExpiryDate(csv_data[1][(int)ReportExchangeDataColumns.ExpiryDate]);
                    data_set.Ppn = csv_data[1][(int)ReportExchangeDataColumns.PZN];
                    data_set.User = csv_data[1][(int)ReportExchangeDataColumns.User];
                    data_set.HiperScanProtocolPdf = String.Empty;

                    data_set.Application = this.ApplicationName;

                    if (csv_data[1].Count > 10)
                    {
                        data_set.WeightCorrFactor = csv_data[1][(int)ReportExchangeDataColumns.WeightCorrFactor];
                        data_set.HasWeightCorrFactor = true;
                    }

                    this.Add(Path.GetFileName(file), data_set);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Cannot import Lennartz-file {0}: {1}", file, ex);
                }
            }
        }

        public override string GetReadingErrorMessage(Exception ex)
        {
            return String.Format(Catalog.GetString(@"Error while reading exchange data: {0}

Possible reasons  are:
- The version of the 'Dr. Lennartz Laboratory' must be at least 5.8.
- The exchange directory does not exist or you do not have the necessary access rights.
- You entered an invalid character at the 'Dr. Lennartz Laboratory'."
                                                          ), ex.Message);
        }


        public override string DefaultWorkingDir 
        {
            get
            {
                return "C:\\Winclip\\Austausch\\Apo-Ident";
            }
        }

        public override string DefaultImportFileExtension
        {
            get
            {
                return "-Out.txt";
            }
        }

        public override string DefaultExportFileExtension
        {
            get
            {
                return "-In.txt";
            }
        }

        public override ProtocolType ProtocolType 
        { 
            get 
            {
                return ProtocolType.Lennartz;
            }
        }

        public override string ApplicationName 
        { 
            get 
            {
                return "Dr. Lennartz";
            }
        }
    }
}
