//
// Program.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2013-2016 Carsten Sonne Larsen
//
// 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.Globalization;
using System.IO;
using System.Threading;
using Ntp.Analyzer.Config;
using Ntp.Analyzer.Export;
using Ntp.Analyzer.Localize;
using Ntp.Config;
using OptionSet = Ntp.Interop.OptionSet;

namespace Ntp.Analyzer.Validate.Cli
{
    public static class Program
    {
        private static bool anyErrors;

        public static void Main(string[] args)
        {
            // Neutralize.
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            bool exit = false;
            bool show = false;
            bool validate = false;
            bool filesystem = false;

            var p =
                new OptionSet
                {
                    {
                        "h|?|help", v =>
                        {
                            ShowUsage();
                            exit = true;
                        }
                    },
                    {
                        "s|show", v => { show = true; }
                    },
                    {
                        "d|default", v => { ConfigurationBase.ShowDefault = true; }
                    },
                    {
                        "v|validate", v => { validate = true; }
                    },
                    {
                        "f|filesystem", v => { filesystem = true; }
                    }
                };

            String[] rem;

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

            if (exit)
            {
                return;
            }

            if (rem.Length > 1)
            {
                Console.WriteLine("Unknown option.");
                return;
            }

            if (rem.Length == 0)
            {
                Console.WriteLine("Please specify configuration file");
                return;
            }

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

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

            if (config == null)
                return;

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

            if (filesystem)
            {
                try
                {
                    TestFilesystem(config);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected error while testing filesystem: " + e.Message);
                    return;
                }

                if (!anyErrors)
                {
                    Console.WriteLine("Filesystem options seems valid.");
                    Console.WriteLine();
                }
            }
        }

        private static Configuration LoadConfig(string configFile)
        {
            if (!File.Exists(configFile))
            {
                Console.WriteLine(InitializationMessage.NoConfig, configFile);
                return null;
            }

            var reader = new ConfigurationReader(configFile);
            if (!reader.Execute())
            {
                foreach (string error in reader.Errors)
                {
                    Console.WriteLine(error);
                }
                return null;
            }

            return reader.Configuration;
        }

        private static void TestFilesystem(ConfigurationBase config)
        {
            try
            {
                foreach (Object item in config)
                {
                    if (item is ConfigurationBase)
                        TestFilesystem(item as ConfigurationBase);
                    else if (item is IEnumerable<ConfigurationBase>)
                    {
                        var items = item as IEnumerable<ConfigurationBase>;

                        foreach (ConfigurationBase subItem in items)
                            TestFilesystem(subItem);
                    }
                    else if (item is StreamDestination)
                    {
                        var destination = item as StreamDestination;
                        destination.Test();
                        Console.WriteLine("Tested " + destination.AbsoluteLocation);
                    }
                }
            }
            catch (Exception ex)
            {
                if (!anyErrors)
                {
                    Console.WriteLine("Error while testing filesystem ...");
                    Console.WriteLine();
                    anyErrors = true;
                }
                Console.WriteLine(ex.Message);
            }
        }

        private static void ShowUsage()
        {
            Console.WriteLine("NTP Analyzer validator tool " + VersionInfo.Text);
            Console.WriteLine(
                "Usage: ntpav [[ --show | -s ] | [ --validate | -v]] [--default | -d] [--filesystem | -f] configuration");
            Console.WriteLine("    -s   Show parsed configuration");
            Console.WriteLine("    -v   Check if configuration is valid");
            Console.WriteLine("    -d   Show all default value");
            Console.WriteLine("    -f   Create configured filesystem paths");
        }
    }
}