﻿//The MIT License(MIT)
//
//Copyright(c) 2016 universalappfactory
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace Sharpend.UAP.Index
{
    [DataContract]
    [KnownType(typeof(IntStringNode))]
    public abstract class BaseIndex<TItem,TId,TToken> where TItem: IIndexableItem<TId> where TId:IComparable<TId>
    {
        private SortedSet<IIndexNode<TId,TToken>> _index;
        protected NodeFactory<TId, TToken> _nodeFactory;
        protected Tokenizer<TItem, TToken> _tokenizer;

        [DataMember]
        public SortedSet<IIndexNode<TId, TToken>> Index 
        {
            get
            {
                return _index;
            }
            protected set
            {
                _index = value;
            }
        }

        protected BaseIndex()
        {
            _index = new SortedSet<IIndexNode<TId, TToken>>();
        }

        public BaseIndex(NodeFactory<TId,TToken> nodeFactory,
            Tokenizer<TItem,TToken> tokenizer)
        {
            if (nodeFactory == null)
            {
                throw new ArgumentNullException("nodeFactory");
            }

            if (tokenizer == null)
            {
                throw new ArgumentNullException("tokenizer");
            }

            _nodeFactory = nodeFactory;
            _tokenizer = tokenizer;
            _index = new SortedSet<IIndexNode<TId,TToken>>();
        }


        [OnDeserializing]
        private void SetValuesOnDeserializing(StreamingContext context)
        {
            Initialize();
        }

        public abstract void Initialize();

        public void Add(TItem item)
        {
            var tokens = _tokenizer.GetTokens(item);

            foreach (var token in tokens)
            {
                var indexNode = _nodeFactory.Create(item.Id, token);
                if (_index.Contains(indexNode))
                {
                    var parent = _index.GetViewBetween(indexNode, indexNode).First();
                    parent.AddChild(item.Id);
                }
                else
                {
                    _index.Add(indexNode);
                }
            }
        }

        public IEnumerable<TId> SearchToken(TToken item)
        {
            List<TId> result = new List<TId>();

            IIndexNode<TId, TToken> searchNode = _nodeFactory.CreateSearchNode(item);

            var parentItem = _index.GetViewBetween(searchNode, searchNode);
            if (parentItem != null)
            {
                result.AddRange(parentItem.Select(p => p.Id));
                result.AddRange(parentItem.SelectMany(p => p.Childen));
                return result;
            }

            return Enumerable.Empty<TId>();
        }

    }
}
