// Created with MonoDevelop
//
//    Copyright (C) 2009 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;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;


namespace Hiperscan.Spectroscopy.Method
{

    public enum SubstanceType
    {
        Solid,
        Fluid,
        SampleInsertOnly,
        NotMeasurable,
    }

    [DataContract(Name = "PcaResult", Namespace = "http://www.hiperscan.com/spectroscopy/method")]
    public class PcaResult : System.Collections.Generic.IEnumerable<PcaMatch>, System.Runtime.Serialization.IExtensibleDataObject
    {
        [DataMember(Order = 0)] public double SignificanceThreshold { get; set; }
        [DataMember(Order = 1)] public double ConfidenceThreshold   { get; set; }
        [DataMember(Order = 2)] public double CorrelationThreshold  { get; set; }
        [DataMember(Order = 3)] public bool IsSorted                { get; set; }

        [DataMember(Name = "PcaMatches", Order = 4)] private readonly List<PcaMatch> matches;

        public Spectrum Spectrum { get; }
        public string Group      { get; set; }

        [NonSerialized] private ExtensionDataObject extension_data;

        private readonly Dictionary<string, PcaMatch> matches_by_name;
        

        public PcaResult()
        {
            this.matches_by_name  = new Dictionary<string,PcaMatch>();
            this.matches          = new List<PcaMatch>();
            this.IsSorted         = false;
            this.Group            = string.Empty;

            this.SignificanceThreshold = 0.0;
            this.ConfidenceThreshold   = 0.0;
            this.CorrelationThreshold  = -1.0;
        }
            
        
        public PcaResult(Spectrum spectrum) : this()
        {
            this.Spectrum = spectrum;
        }
        
        public void Add(PcaMatch match)
        {
            this.IsSorted = false;
            this.matches.Add(match);
            this.matches_by_name.Add(match.Id, match);
        }

        private void Sort()
        {
            if (this.IsSorted)
                return;
            
            this.matches.Sort();
            this.matches.Reverse();

            for (int ix = 0; ix < this.matches.Count; ++ix)
            {
                this.matches[ix].SetRanking(ix);
            }
            
            this.IsSorted = true;
        }
        
        public IEnumerator<PcaMatch> GetEnumerator()
        {
            foreach (PcaMatch match in this.matches)
            {
                yield return match;
            }
        }
        
        IEnumerator IEnumerable.GetEnumerator()
        { 
            return GetEnumerator();    
        }
        
        public bool ExceedsThresholds(PcaMatch match)
        {
            return (match.Significance >= this.SignificanceThreshold &&
                    match.Confidence   >= this.ConfidenceThreshold   &&
                    match.Correlation  >= this.CorrelationThreshold);
        }

        public PcaMatch this[string name]
        {
            get
            {
                this.Sort();
                return this.matches_by_name[name];
            }
        }
        
        public int Count
        {
            get { return this.matches.Count; }
        }

        public PcaMatch this[int ranking]
        {
            get
            {
                this.Sort();
                return this.matches[ranking];
            }
        }
        
        public bool HasMatch
        {
            get
            {
                if (this.matches.Count < 1)
                    return false;
                
                return (this.matches[0].Significance >= this.SignificanceThreshold &&
                        this.matches[0].Confidence   >= this.ConfidenceThreshold   &&
                        this.matches[0].Correlation  >= this.CorrelationThreshold);
            }
        }

        public static void Write(PcaResult pca_result, string fname)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = "\t";
            //settings.NewLineOnAttributes = true;
            settings.NewLineChars = "\n";

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

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

        public ExtensionDataObject ExtensionData
        {
            get { return this.extension_data; }
            set { this.extension_data = value; }
        }
    }
}