// 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.Extensions.ApoIdent
{
    public class DataExchangeLennartz : DataExchange
    {
        private enum ReportExchangeDataColumns
        {
            Key,
            PrimarySubstanceName,
            HiperScanSubstanceId,
            Supplier,
            BatchNumber,
            TypeOfDate,
            ExpiryDate,
            PZN,
            User,
            HiperScanProtocolPdf,
            WeightCorrFactor,
        }

        public DataExchangeLennartz()
        {
        }

        protected override DateTime ConvertToExpirationDate(string date)
        {
            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);
        }

        protected override void DeleteImportFile()
        {
            try
            {
                File.Delete(Path.Combine(this.WorkingDir, this.CurrentDataSetKey));
            }
            catch(Exception)
            {
            }
        }

        public override void ExportFile(ReportInfo report_info)
        {
            this.ExportSuccess = false;
            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 = report_info.PdfFileFullName;

            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].Supplier);
            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"));
            csv_data[1].Add(this[this.CurrentDataSetKey].PZN);
            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();
            this.ExportSuccess = true;
        }

        public override void ImportFiles()
        {
            this.ExportSuccess = false;
            this.Clear();

            string pattern = "*" + this.DefaultImportFileExtension;
            foreach (string file in Directory.GetFiles(this.WorkingDir, pattern))
            {
                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.Supplier               = csv_data[1][(int)ReportExchangeDataColumns.Supplier];
                data_set.BatchNumber            = csv_data[1][(int)ReportExchangeDataColumns.BatchNumber];
                data_set.TypeOfDate             = csv_data[1][(int)ReportExchangeDataColumns.TypeOfDate];
                data_set.ExpiryDate             = this.ConvertToExpirationDate( csv_data[1][(int)ReportExchangeDataColumns.ExpiryDate]);
                data_set.PZN                    = csv_data[1][(int)ReportExchangeDataColumns.PZN];
                data_set.User                   = csv_data[1][(int)ReportExchangeDataColumns.User];
                data_set.HiperScanProtocolPdf   = String.Empty;

                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);
            }
        }

        public override string GetReadingErrorMessage(Exception ex)
        {
            return String.Format(Catalog.GetString("Error while reading exchange data: {0}\n\n" +
                                                           "Possible reasons  are:\n" +
                                                          "- The version of the 'Dr. Lennartz labratpry program' must be at least 5.8.\n" +
                                                          "- The exchange directory doesn't exist or you don't have the necessary access rights.\n" +
                                                          "- You entered a not allow character \" at the 'Dr. Lennartz labratpry program'."
                                                          ), 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";
            }
        }
    }
}
