// 
// 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.Globalization;
using System.IO;
using System.Threading;
using Ntp.Analyzer.Config;
using Ntp.Analyzer.Config.Compiler;
using Ntp.Analyzer.Config.Node;
using Ntp.Common.IO;

namespace Ntp.Analyzer.Validate.Cli
{
    public static class Program
    {
        private const int ParameterErrorCode = 2;
        private const int ConfigErrorCode = 1;
        private const int SuccessCode = 0;
        private static bool usage;

        public static int Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            bool validate = false;
            bool show = false;

            var dec = new Decompiler();
            var param = new OptionSet
            {
                {"h|?|help", v => { ShowUsage(); }},
                {"s|show", v => { show = true; }},
                {"d|default", v => { dec.ShowDefaultValues = true; }},
                {"v|validate", v => { validate = true; }},
                {"t=|tabs=", v => SetDecompilerParam(dec, '\t', v)},
                {"w=|whitespace=", v => SetDecompilerParam(dec, ' ', v)}
            };

            string[] rem;

            try
            {
                rem = param.Parse(args).ToArray();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return ParameterErrorCode;
            }

            if (usage)
            {
                return ParameterErrorCode;
            }

            if (rem.Length != 1)
            {
                Console.WriteLine("Wrong parameters.");
                return ParameterErrorCode;
            }

            if (!show && !validate)
            {
                ShowUsage();
                return ParameterErrorCode;
            }

            Configuration config;
            try
            {
                config = LoadConfig(rem[0]);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Unexpected error while loading configuration file: {e.Message}");
                return ConfigErrorCode;
            }

            if (config == null)
                return ConfigErrorCode;

            if (show)
            {
                dec.Configuration = config;
                Console.Write(dec.Execute());
            }
            else if (validate)
            {
                Console.WriteLine("Configuration is valid.");
            }

            return SuccessCode;
        }

        private static Configuration LoadConfig(string configFile)
        {
            if (!File.Exists(configFile))
            {
                Console.WriteLine($"Cannot find configuration file {configFile}");
                return null;
            }

            var reader = new ConfigBuilder(configFile);
            var config = reader.Execute();
            if (config != null)
                return config;

            foreach (string error in reader.Errors)
            {
                Console.WriteLine(error);
            }

            return null;
        }

        private static void SetDecompilerParam(Decompiler decompiler, char indent, string count)
        {
            int parsed;
            decompiler.IndentChar = indent;
            decompiler.IndentSize = int.TryParse(count, out parsed) ? parsed : 1;
        }

        private static void ShowUsage()
        {
            Console.WriteLine("NTP Analyzer validator tool v0.8.1");
            Console.WriteLine("Usage: ntpav [-s|-v] [-d] [-t n|-w n] configuration");
            Console.WriteLine("    -s   Show parsed configuration");
            Console.WriteLine("    -v   Check if configuration is valid");
            Console.WriteLine("    -d   Show all default value");
            Console.WriteLine("    -t   Indent with n tabulators");
            Console.WriteLine("    -w   Indent with n whitespaces");
            usage = true;
        }
    }
}