// 
// Copyright (c) 2013-2016 Carsten Sonne Larsen <cs@innolan.dk>
// 
// 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.Collections.Generic;
using System.Linq;
using Ntp.Analyzer.Config.Node;
using Ntp.Analyzer.Config.Syntax.Option;
using Ntp.Analyzer.Config.Syntax.Setting;
using Ntp.Analyzer.Config.Table;

namespace Ntp.Analyzer.Config.Syntax
{
    public sealed class StatSyntaxNode : SyntaxNode<StatConfiguration>
    {
        public StatSyntaxNode(Symbol symbol, string name, int line)
            : base(symbol, name, line)
        {
        }

        private ReadingSyntaxNode bulk;

        protected override StatConfiguration InternalCompile()
        {
            var initialRun = Nodes.SingleOrDefault(n => n.Symbol == Symbol.KeywordInitialRun) as BooleanSettingNode;
            var fixedRun = Nodes.SingleOrDefault(n => n.Symbol == Symbol.KeywordFixedRun) as BooleanSettingNode;
            var stamp = Nodes.SingleOrDefault(n => n.Symbol == Symbol.KeywordTimeStamp) as TimeStampNode;

            var freq = bulk == null
                ? Nodes.SingleOrDefault(n => n.Symbol == Symbol.KeywordFrequency) as IntegerSettingNode
                : null;

            if (Symbol != Symbol.KeywordDriftStats)
                return new StatConfiguration(
                    Name,
                    bulk?.Compile(),
                    stamp?.DateTimeKind,
                    freq?.Value,
                    initialRun?.Value,
                    fixedRun?.Value);

            var file = Nodes.SingleOrDefault(n => n.Symbol == Symbol.KeywordFile) as StringSettingNode;

            return new DriftStatConfiguration(
                Name,
                file?.Value,
                bulk?.Compile(),
                stamp?.DateTimeKind,
                freq?.Value,
                initialRun?.Value,
                fixedRun?.Value);
        }

        protected override void InternalResolve(SymbolTable table)
        {
            var freq = Nodes.SingleOrDefault(n => n.Symbol == Symbol.KeywordFrequency) as StringSettingNode;
            if (freq != null)
                bulk = table.Lookup(freq.Value) as ReadingSyntaxNode;
        }

        protected override void ValidateMandatories()
        {
            CheckIsUnique(new List<Symbol>
            {
                Symbol.KeywordInitialRun,
                Symbol.KeywordFixedRun,
                Symbol.KeywordFrequency,
                Symbol.KeywordTimeStamp,
                Symbol.KeywordFile
            });

            CheckAllIsPresent(new List<Symbol> {Symbol.KeywordFrequency});

            if (Symbol == Symbol.KeywordDriftStats)
            {
                CheckAllIsPresent(new List<Symbol> {Symbol.KeywordFile});
            }
        }

        protected override void ValidateReferences(SymbolTable table)
        {
            string keyword = Keyword.Find(Symbol.KeywordFrequency).Name;
            string name = Keyword.Find(Symbol.KeywordReading).Name;

            var freq = Nodes.SingleOrDefault(n => n.Symbol == Symbol.KeywordFrequency);
            if (!(freq is IntegerSettingNode || freq is StringSettingNode))
            {
                AddError($"{keyword} must be either an integer value or the name of a {name} section.");
            }

            var freqName = freq as StringSettingNode;
            if (freqName == null)
                return;

            var reference = table.Lookup(freqName.Value);
            if (reference == null)
            {
                AddReferenceNameError(freqName, keyword, freqName.Value);
            }
            else if (!(reference is ReadingSyntaxNode))
            {
                AddRefrenceTypeError(freqName, keyword, name, freqName.Value);
            }

            if (Symbol == Symbol.KeywordDriftStats || Nodes.Count(n => n.Symbol == Symbol.KeywordFile) == 0)
                return;

            string fileKeyword = Keyword.Find(Symbol.KeywordFile).Name;
            string sectionKeyword = Keyword.Find(Symbol).Name;
            AddError($"{fileKeyword} is not a valid setting in a {sectionKeyword} section.");
        }

        protected override void ValidateTypes()
        {
            CheckTypeIs<BooleanSettingNode>(Symbol.KeywordInitialRun);
            CheckTypeIs<BooleanSettingNode>(Symbol.KeywordFixedRun);
            CheckTypeIs<TimeStampNode>(Symbol.KeywordTimeStamp);
            CheckTypeIs<IntegerSettingNode, StringSettingNode>(Symbol.KeywordFrequency);
            CheckTypeIs<StringSettingNode>(Symbol.KeywordFile);
        }
    }
}