// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2022, 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.Text;

using Hiperscan.AnalysisModule.Authentification;
using Hiperscan.AnalysisModule.Identification;
using Hiperscan.Common;
using Hiperscan.ApoIdentCommon.ApoConfig.IO;
using Hiperscan.Unix;

namespace Hiperscan.ApoIdentCommon.ApoConfig.Cache
{
    public partial class ModelExtension : SecureFileWriter
    {
        public ModelExtension() : base()
        {
        }

        public ModelExtension(string file_name, int repeats = 5) : base(file_name, repeats)
        {
        }

        public override void Clear()
        {
            this.ModelClass = new IdentModelClass();
            this.ModelClass.DatabaseInfo = IdentModelClass.GetUserDefinedDatabaseInfo();
            this.ModelClass.InitResolver();
            this.OldHashCode = this.GetModelClassHashCode();
        }

        public void LoadExtension(string file_name, bool directory_changed)
        {
            ModelExtension tmp = new ModelExtension(file_name);

            if (directory_changed == true)
            {
                if (tmp.FoundData == true)
                {
                    this.ModelClass = tmp.ModelClass;
                    this.OldHashCode = tmp.OldHashCode;
                }
                else
                {
                    this.SafetyWrite(file_name);
                }
            }
            else
            {
                this.ModelClass = tmp.ModelClass;
                this.OldHashCode = tmp.OldHashCode;
            }
        }

        public void SaveExtension(string file_name)
        {
            this.SafetyWrite(file_name);
        }

        public void Add(IdentModelClass model_class, string file)
        {
            if (model_class == null)
                return;

            if (this.ModelClass.Classifications.Count > 0)
                return;

            if (model_class.DatabaseInfo.DatabaseType != AccessDatabaseType.UserDefined)
                return;

            this.ModelClass = model_class;
            try
            {
                this.SaveExtension(file);
            }
            catch(Exception ex)
            {
                Console.WriteLine("Cannot save model extensions: {0}", ex);
            }
        }

        protected override void Write(string file_name)
        {
            DataSerializer.Write<IdentModelClass>(this.ModelClass, file_name);
            this.OldHashCode = this.GetModelClassHashCode();
        }

        protected override void Read(string file_name)
        {
            try
            {
                this.ModelClass = DataSerializer.Read<IdentModelClass>(file_name);
            }
            catch (Exception)
            {
                try
                {
                    this.ModelClass = GetLegacyModelClass(file_name);
                    this.SafetyWrite(file_name);
                }
                catch(Exception)
                {
                    this.ModelClass = new IdentModelClass();
                }
            }

            this.ModelClass.DatabaseInfo = IdentModelClass.GetUserDefinedDatabaseInfo();
            this.ModelClass.InitResolver();
            this.OldHashCode = this.GetModelClassHashCode();
        }

        private int GetModelClassHashCode()
        {
            if (this.ModelClass == null)
                return String.Empty.GetHashCode();

            StringBuilder text = new StringBuilder();
            foreach (IdentClassification classification in this.ModelClass.Classifications)
            {
                foreach (IdentSubstance substance in classification.Substances)
                    text.Append(substance.IsVisible.ToString());

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

            text.Append(this.FileName);
            return text.ToString().GetHashCode();
        }

        public override bool HasWritingData
        {
            get
            {
                return this.ModelClass.Classifications.Count > 0 &&
                           (this.OldHashCode != this.GetHashCode() ||
                            false == FileIO.ExistsFile(this.FileName));
            }
        }

        public IdentModelClass ModelClass { get; private set; } = new IdentModelClass();
        private int OldHashCode { get; set; }
    }
}
