//
// Program.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2013 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.Config;

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;

            if (args.Length == 0 || args.Length > 2) {
                ShowUsage ();
                return;
            }

            if (args.Length == 1 && args[0] == "help") {
                ShowUsage ();
                return;
            }

            string configFile = args [0];

            Configuration config = LoadConfig (configFile);
            if (config == null) {
                return;
            }

            Console.WriteLine ("Parsed config ...");

            if (args.Length == 2 && args [1] == "verbose") {
                Console.WriteLine (config);
            }

            TestFilesystem (config);

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

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

            Configuration config = null;

            // Read config.
            try {
                string[] configLines = File.ReadAllLines (configFile);
                ConfigurationBlock block = new ConfigurationBlock (configLines);
                config = Configuration.Create (block);
            } catch (Exception ex) {
                Console.WriteLine ("Cannot read configuration file: " + configFile);
                Console.WriteLine (ex.Message);
                return null;
            }

            if (ConfigurationBase.Errors != String.Empty) {
                Console.WriteLine ("Errors in configuration file");
                Console.WriteLine (ConfigurationBase.Errors);
                return null;
            }

            return config;
        }

        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>) {
                        IEnumerable<ConfigurationBase> items = item as IEnumerable<ConfigurationBase>;

                        foreach (ConfigurationBase subItem in items)
                            TestFilesystem (subItem);
                    } else if (item is StreamDestination) {
                        StreamDestination 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.");
            Console.WriteLine ("Usage: ntpav configuration [verbose]");
        }
    }
}