// Created with MonoDevelop
//
//    SearchIPAddr: find spectrometer in local network
//    Copyright (C) 2020 A. Höpfner, 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 System.Runtime.Serialization;
using System.Xml;
using Hiperscan.Unix;

namespace Hiperscan.Spectroscopy.IdentModule.ValidationReportInfo
{
    [DataContract(Name = "ClassifierReportInfo", Namespace = "http://www.hiperscan.com/spectroscopy/identmodule/validationreportinfo")]
    [Serializable()]
    public class ClassifierReportInfo : System.Runtime.Serialization.IExtensibleDataObject
    {
        public const string FILE_EXTENSION = "cri";

        public static void Write(ClassifierReportInfo classifier_report_info, string fname)
        {
            XmlWriterSettings settings = new XmlWriterSettings
            {
                Indent = true,
                IndentChars = "\t",
                NewLineOnAttributes = true,
                NewLineChars = "\n"
            };

            fname = Path.ChangeExtension(fname, ClassifierReportInfo.FILE_EXTENSION);

            using (XmlWriter writer = XmlWriter.Create(fname, settings))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(ClassifierReportInfo));

                // we want to register a global namespace to prevent thousands of repeats
                serializer.WriteStartObject(writer, classifier_report_info);
                writer.WriteAttributeString("xmlns", "p", null, "http://schemas.microsoft.com/2003/10/Serialization/Arrays");
                writer.WriteAttributeString("xmlns", "q", null, "http://www.hiperscan.com/spectroscopy");
                serializer.WriteObjectContent(writer, classifier_report_info);
                serializer.WriteEndObject(writer);
            }
        }


        public static ClassifierReportInfo Read(Stream stream)
        {
            using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(ClassifierReportInfo));
                ClassifierReportInfo classifier_report_info = (ClassifierReportInfo)serializer.ReadObject(reader, true);
                return classifier_report_info;
            }
        }

        public static ClassifierReportInfo Read(string fname)
        {
            using (Stream stream = new FileStream(fname, FileMode.Open, FileAccess.Read))
            {
                return ClassifierReportInfo.Read(stream);
            }
        }

        public bool Check()
        {
            bool success = true;

            foreach (ClassificationReportInfo classification in this.Classifications.Values)
            {
                if (this.CheckValidationEntries(classification) == false)
                    success = false;
            }

            return success;
        }

        private bool CheckValidationEntries(ClassificationReportInfo classification)
        {
            bool success = true;

            ValidationsTable validation_table = classification.ValidationsTable;

            foreach (ValidationTypes type in Enum.GetValues(typeof(ValidationTypes)))
            {
                try
                {
                    Int32.Parse(validation_table.TruePositive[type]);
                }
                catch (Exception)
                {
                    string message = String.Format(Catalog.GetString("Classsification {0} (Id = {1} -> " +
                                   "ValidationTable -> Validationtype {2} -> " +
                                   "TruePositive is not a number"),
                                   classification.ClassificationName,
                                   classification.ClassificationId,
                                   type);

                    this.Criticals.Add(message);
                    success = false;
                }

                try
                {
                    Int32.Parse(validation_table.TrueNegative[type]);
                }
                catch(Exception)
                {
                    string message = String.Format(Catalog.GetString("Classsification {0} (Id = {1} -> " +
                                   "ValidationTable -> Validationtype {2} -> " +
                                   "TrueNegative is not a number"),
                                   classification.ClassificationName,
                                   classification.ClassificationId,
                                   type);

                    this.Criticals.Add(message);
                    success = false;
                }

                try
                {
                    Int32.Parse(validation_table.FalsePositive[type]);
                }
                catch (Exception)
                {
                    string message = String.Format(Catalog.GetString("Classsification {0} (Id = {1} -> " +
                                   "ValidationTable -> Validationtype {2} -> " +
                                   "FalsePositive is not a number"),
                                   classification.ClassificationName,
                                   classification.ClassificationId,
                                   type);

                    this.Criticals.Add(message);
                    success = false;
                }

                try
                {
                    Int32.Parse(validation_table.FalseNegative[type]);
                }
                catch (Exception)
                {
                    string message = String.Format(Catalog.GetString("Classsification {0} (Id = {1} -> " +
                                   "ValidationTable -> Validationtype {2} -> " +
                                   "FalseNegative is not a number"),
                                   classification.ClassificationName,
                                   classification.ClassificationId,
                                   type);

                    this.Criticals.Add(message);
                    success = false;
                }
            }

            return success;
        }

        [NonSerialized] ExtensionDataObject extension_data = null;
        public ExtensionDataObject ExtensionData
        {
            get { return this.extension_data; }
            set { this.extension_data = value; }
        }

        public List<string> Criticals { get; private set; } = new List<string>();

        [DataMember] public string ClassifierName { get; set; } = String.Empty;
        [DataMember] public string ClassifierId { get; set; } = String.Empty;
        [DataMember] public Guid Guid { get; set; } = Guid.Empty;

        [DataMember] public Dictionary<string, ClassificationReportInfo> Classifications { get; private set; } = new Dictionary<string, ClassificationReportInfo>();
    }
}
