// 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.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Xml;
using Hiperscan.Spectroscopy.IdentModule;


namespace Hiperscan.Extensions.ApoIdent
{
    public class SubstanceExtension
    {
        public SubstanceExtension(IdentServerClient client)
        {
            bool load_from_ident_module = true;

            for (int i = 0; i < 5; i++)
            {
                try
                {
                    if (File.Exists(FilesAndDirs.ModelClassExtensionFile) == true)
                    {
                        this.SetModelClassExtension(ModelClassExtensionInfo.Read(FilesAndDirs.ModelClassExtensionFile));
                        load_from_ident_module = false;
                        break;
                    }

                }
                catch (Exception ex)
                {
                    if (i == 4)
                        Console.WriteLine("Could not read model extension class (try1);{0}", ex);
                    Thread.Sleep(50);
                }

                try
                {
                    if (File.Exists(FilesAndDirs.ModelClassExtensionBackupFile) == true)
                    {
                        this.SetModelClassExtension(ModelClassExtensionInfo.Read(FilesAndDirs.ModelClassExtensionBackupFile));
                        load_from_ident_module = false;
                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (i == 4)
                        Console.WriteLine("Could not read model extension class (try2);{0}", ex);
                    Thread.Sleep(50);
                }
            }

            try
            {
                if (load_from_ident_module == true)
                {
                    this.SetModelClassExtension(client.GetModelClassExtensionInfo());
                }
            }
            catch (Exception ex)
            {
                if (ApoIdentEnvs.DebugOn)
                    Console.WriteLine("Could not read initial model extension class;{0}", ex);

                this.SetModelClassExtension(new ModelClassExtensionInfo());
            }

            this.OldHashCode = this.GetHashCode();
            this.GetModelClassExtension().ModelClassName = LocalizedSubstanceExtensions.UserDefinedModelClassName;

            try
            {
                this.Save(true);
            }
            catch(Exception)
            {

            }
        }

        public void Save(bool force)
        {
            if (this.GetModelClassExtension().Classifications.Count == 0)
                return;

            int hash_code = this.GetHashCode();
    
            if (force == false && this.OldHashCode == hash_code)
                return;

            try
            {
                FilesAndDirs.CreateMetaDataDir();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Cannot create .meta directory: {0}", ex);
                return;
            }

            for (int i = 0; i < 5; i++)
            {
                try
                {
                    ModelClassExtensionInfo.Write(this.GetModelClassExtension(), FilesAndDirs.ModelClassExtensionFile);
                    ModelClassExtensionInfo.Read(FilesAndDirs.ModelClassExtensionFile);
                    this.OldHashCode = hash_code;
                }
                catch (Exception ex)
                {
                    if (i == 4)
                    {
                        Console.WriteLine("Error while saving substance extension: {0}", ex);
                        return;
                    }
                    Thread.Sleep(50);
                }
            }

            try
            {
                File.Copy(FilesAndDirs.ModelClassExtensionFile, FilesAndDirs.ModelClassExtensionBackupFile, true);
            }
            catch (Exception ex)
            {
                if (ApoIdentEnvs.DebugOn)
                    Console.WriteLine("Error while copying model class extension; {0}", ex);
            }
        }

        private string GetRelevantTextForComparison()
        {
            StringBuilder text = new StringBuilder();
            foreach (ClassificationInfo classification_info in this.GetModelClassExtension().Classifications)
            {
                foreach (SubstanceInfo substance_info in classification_info.Substances)
                    text.Append(substance_info.IsVisible.ToString());

                if (classification_info.IsUserDefined)
                    text.Append(classification_info.Id);
            }

            text.Append(FilesAndDirs.AdditionalDocuDir);
            return text.ToString();
        }

        public override int GetHashCode()
        {
            return this.GetRelevantTextForComparison().GetHashCode();
        }


        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            if (this == obj)
                return true;

            SubstanceExtension tmp = obj as SubstanceExtension;
            if (tmp == null)
                return false;

            return this.GetRelevantTextForComparison() == tmp.GetRelevantTextForComparison();
        }

        public ModelClassExtensionInfo GetModelClassExtension()
        {
            return this.ModelClassExtension;
        }

        private void SetModelClassExtension(ModelClassExtensionInfo value)
        {
            this.ModelClassExtension = value;
        }

        private ModelClassExtensionInfo ModelClassExtension { get; set; } = new ModelClassExtensionInfo();

        private int OldHashCode {get; set;}
    }
}
