// 
// 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;
using System.Collections;
using System.Linq;
using System.Reflection;
using System.Text;
using Ntp.Analyzer.Config.Attribute;
using Ntp.Analyzer.Config.Node;
using Ntp.Analyzer.Config.Table;
using Ntp.Analyzer.Interface;

namespace Ntp.Analyzer.Config.Compiler
{
    public sealed class Decompiler
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Decompiler" /> class.
        /// </summary>
        public Decompiler()
        {
            IndentChar = ' ';
            IndentSize = 8;
        }

        private StringBuilder builder;

        /// <summary>
        /// Gets or sets the Configuration to decompile.
        /// </summary>
        /// <value>The configuration.</value>
        public Configuration Configuration { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="Decompiler" /> show default
        /// values.
        /// </summary>
        /// <value><c>true</c> if show default values; otherwise, <c>false</c>.</value>
        public bool ShowDefaultValues { get; set; }

        /// <summary>
        /// Gets or sets the indent char.
        /// </summary>
        /// <value>The indent char.</value>
        public char IndentChar { get; set; }

        /// <summary>
        /// Gets or sets the size of the indent.
        /// </summary>
        /// <value>The size of the indent.</value>
        public int IndentSize { get; set; }

        /// <summary>
        /// Execute the decompiler.
        /// </summary>
        /// <returns>Decompiled configuration as text.</returns>
        public string Execute()
        {
            builder = new StringBuilder();
            DecompileConfiguration(-1, null, Configuration);
            return builder.ToString();
        }

        private void AppendDateTimeKind(DateTimeKind value)
        {
            switch (value)
            {
                case DateTimeKind.Local:
                    builder.Append(Keyword.Find(Symbol.KeywordTimeStampLocal).Name);
                    break;
                case DateTimeKind.Utc:
                case DateTimeKind.Unspecified:
                    builder.Append(Keyword.Find(Symbol.KeywordTimeStampUtc).Name);
                    break;
                default:
                    builder.Append(Keyword.Find(Symbol.KeywordTimeStampUtc).Name);
                    break;
            }
        }

        /// <summary>
        /// Appends indent to output.
        /// </summary>
        /// <param name="size">Indent size.</param>
        private void AppendIndent(int size)
        {
            builder.Append(string.Empty.PadLeft(size*IndentSize, IndentChar));
        }

        /// <summary>
        /// Appends the string to output.
        /// </summary>
        /// <param name="value">Value of node.</param>
        /// <param name="layout">Special layout properties.</param>
        /// <param name="indent">Indent count.</param>
        private void AppendString(string value, Layout layout, int indent)
        {
            switch (layout)
            {
                case Layout.Block:
                    builder.AppendLine("{ ");
                    var lines = value.Trim().Split(
                        new[] {Environment.NewLine},
                        StringSplitOptions.None
                        );
                    foreach (var line in lines)
                    {
                        AppendIndent(indent + 1);
                        builder.AppendLine(line.Trim());
                    }
                    AppendIndent(indent);
                    builder.Append("}");
                    break;
                case Layout.Quoted:
                    builder.Append("\"");
                    builder.Append(value);
                    builder.Append("\"");
                    break;
                case Layout.Normal:
                    if (value.Contains(" ") || value.Contains("\t"))
                    {
                        builder.Append("\"");
                        builder.Append(value);
                        builder.Append("\"");
                    }
                    else
                    {
                        builder.Append(value);
                    }
                    break;
                default:
                    builder.Append(value);
                    break;
            }
        }

        /// <summary>
        /// Decompiles a complex node type (classes).
        /// </summary>
        /// <param name="indent">Indent count.</param>
        /// <param name="node">Configuration node to decompile.</param>
        private void DecompileComplexType(int indent, object node)
        {
            var properties = node.GetType().GetProperties().
                OrderBy(
                    delegate(PropertyInfo info)
                    {
                        var attribute = System.Attribute.GetCustomAttribute(info, typeof(NtpaIndex));
                        return ((NtpaIndex) attribute)?.Index ?? int.MaxValue;
                    });

            foreach (var property in properties)
            {
                if (DecompileSetting(indent, node, property))
                    continue;

                if (DecompileSettingCollection(indent, node, property))
                    continue;

                if (DecompileReferenceCollection(indent, node, property))
                    continue;

                DecompileReference(indent, node, property);
            }
        }

        /// <summary>
        /// Decompiles a configuration section.
        /// </summary>
        /// <param name="indent">Indent count</param>
        /// <param name="typeName">Name of configuration section.</param>
        /// <param name="node">Configuration node to decompile.</param>
        private void DecompileConfiguration(int indent, string typeName, IConfigurationNode node)
        {
            if (node == null)
                return;

            // Swap builders
            var temp = builder;
            builder = new StringBuilder();

            DecompileComplexType(indent + 1, node);

            // Swap builder back
            var res = builder;
            builder = temp;

            // Skip empty nodes
            if (res.ToString().Trim() == string.Empty)
                return;

            if (indent >= 0)
            {
                // Make a blank line
                AppendIndent(indent);
                builder.AppendLine();

                // Write header
                AppendIndent(indent);
                builder.Append(typeName);

                if (node.ConfigName != null)
                {
                    builder.Append(" ");
                    builder.Append(node.ConfigName);
                }

                builder.AppendLine(" {");
            }

            builder.Append(res);

            if (indent >= 0)
            {
                AppendIndent(indent);
                builder.AppendLine("}");
            }
        }

        /// <summary>
        /// Decompiles a reference property if applicable.
        /// </summary>
        /// <param name="indent">Indent count.</param>
        /// <param name="node">Configuration node to decompile.</param>
        /// <param name="property">Property to decompile.</param>
        private void DecompileReference(int indent, object node, PropertyInfo property)
        {
            var reference = (NtpaReference) System.Attribute.GetCustomAttribute(property, typeof(NtpaReference));
            if (reference == null)
                return;

            var value = property.GetValue(node, null);
            if (value == null)
                return;

            var keyword = Keyword.Find(reference.Keyword);
            var configurationNode = value as IConfigurationNode;
            if (configurationNode == null)
                return;

            var name = configurationNode.ConfigName;
            DecompileSimpleType(indent, keyword.Name, name, null, Layout.Normal);
        }

        /// <summary>
        /// Decompiles a property with a collection of references if applicable.
        /// </summary>
        /// <param name="indent">Indent count.</param>
        /// <param name="node">Configuration node to decompile.</param>
        /// <param name="property">Property to decompile.</param>
        /// <returns><c>true</c> if property is a collection of references; otherwise, <c>false</c>.</returns>
        private bool DecompileReferenceCollection(int indent, object node, PropertyInfo property)
        {
            var attribute = System.Attribute.GetCustomAttribute(property, typeof(NtpaReferenceCollection));
            if (attribute == null)
                return false;

            var refCollection = (NtpaReferenceCollection) attribute;

            var value = property.GetValue(node, null);
            if (!(value is IEnumerable))
                return true;

            var keyword = Keyword.Find(refCollection.Keyword);
            foreach (var subObject in value as IEnumerable)
            {
                var configurationNode = subObject as IConfigurationNode;
                if (configurationNode != null)
                {
                    var name = configurationNode.ConfigName;
                    DecompileSimpleType(indent, keyword.Name, name, null, Layout.Normal);
                }
            }

            return true;
        }

        /// <summary>
        /// Decompiles a setting property if applicable.
        /// </summary>
        /// <param name="indent">Indent count.</param>
        /// <param name="node">Configuration node to decompile.</param>
        /// <param name="property">Property to decompile.</param>
        /// <returns><c>true</c> if property is a setting; otherwise, <c>false</c>.</returns>
        private bool DecompileSetting(int indent, object node, PropertyInfo property)
        {
            var setting = (NtpaSetting) System.Attribute.GetCustomAttribute(property, typeof(NtpaSetting));
            if (setting == null)
                return false;

            var keyword = Keyword.Find(setting.Keyword);
            var value = property.GetValue(node, null);
            if (value == null)
                return true;

            if (value is IConfigurationNode)
            {
                DecompileConfiguration(indent, keyword.Name, value as IConfigurationNode);
            }
            else
            {
                DecompileSimpleType(indent, keyword.Name, value, setting.Value, setting.Layout);
            }

            return true;
        }

        /// <summary>
        /// Decompiles a collection property if applicable.
        /// </summary>
        /// <param name="indent">Indent count.</param>
        /// <param name="node">Configuration node to decompile.</param>
        /// <param name="property">Property to decompile.</param>
        /// <returns><c>true</c> if property is a collection; otherwise, <c>false</c>.</returns>
        private bool DecompileSettingCollection(int indent, object node, PropertyInfo property)
        {
            var attribute = System.Attribute.GetCustomAttribute(property, typeof(NtpaSettingsCollection));
            if (attribute == null)
                return false;

            var collection = (NtpaSettingsCollection) attribute;

            var value = property.GetValue(node, null);
            if (value == null)
                return true;

            // Decompile the collection in flat style
            if (collection.Flatten && value is IEnumerable)
            {
                foreach (var subObject in value as IEnumerable)
                {
                    DecompileComplexType(indent, subObject);
                }
                return true;
            }

            if (!(value is IEnumerable))
                return true;

            var raiseAdd = 0;
            if (collection.Raise != Symbol.Undefined)
            {
                var raise = Keyword.Find(collection.Raise);
                AppendIndent(indent);
                builder.Append(raise.Name);
                builder.AppendLine(" {");
                raiseAdd = 1;
            }

            var keyword = Keyword.Find(collection.Keyword);
            foreach (var subObject in value as IEnumerable)
            {
                DecompileConfiguration(indent + raiseAdd, keyword.Name, subObject as IConfigurationNode);
            }

            if (collection.Raise != Symbol.Undefined)
            {
                AppendIndent(indent);
                builder.AppendLine("}");
            }

            return true;
        }

        /// <summary>
        /// Decompiles a simple node type (integers, strings, etc.)
        /// </summary>
        /// <param name="indent">Indent count.</param>
        /// <param name="name">The name of the node.</param>
        /// <param name="value">The value of the node.</param>
        /// <param name="defaultValue">Default value for this type.</param>
        /// <param name="layout">Special layout properties.</param>
        private void DecompileSimpleType(int indent, string name, object value, object defaultValue, Layout layout)
        {
            if (!ShowDefaultValues && value.Equals(defaultValue))
                return;

            if (layout == Layout.Block)
            {
                AppendIndent(indent);
                builder.AppendLine();
            }

            AppendIndent(indent);
            builder.Append(name);
            builder.Append(" ");

            if (value is bool)
            {
                builder.Append((bool) value ? "Yes" : "No");
            }
            else if (value is string)
            {
                AppendString((string) value, layout, indent);
            }
            else if (value is DateTimeKind)
            {
                AppendDateTimeKind((DateTimeKind) value);
            }
            else if (value is Uri)
            {
                AppendString(((Uri) value).OriginalString, layout, indent);
            }
            else
            {
                builder.Append(value);
            }

            builder.AppendLine();
        }
    }
}