﻿namespace TakeOwnership
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Windows.Forms;
    using Properties;
    using SilDev;

    internal class Program
    {
        private static string _argument = string.Empty;

        private static void Main()
        {
            if (Environment.OSVersion.Version.Major < 10)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                MessageBox.Show(Resources.MsgWarnOS);
                return;
            }
            Log.AllowLogging();
            var hasParentCon = ProcessEx.CurrentParent?.ProcessName.EqualsEx("cmd", "powershell", "powershell_ise") == true;
            try
            {
                Console.Title = Resources.Title;
                Console.BackgroundColor = ConsoleColor.Black;
                Console.SetBufferSize(short.MaxValue - 1, Console.WindowWidth);
                Console.SetWindowSize(Math.Min(120, Console.LargestWindowWidth), Math.Min(55, Console.LargestWindowHeight));
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine(Resources.Logo);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(Resources.LogoText);
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.WriteLine(Resources.LogoBuild, Data.GetVersion(PathEx.LocalPath));
                Console.WriteLine();
                var args = EnvironmentEx.CommandLineArgs(false, false).ToArray();
                if (args.Length == 0 || args.Length == 1 && args[0].StartsWith("/"))
                {
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine(Resources.Help);
                    Console.WriteLine();
                    if (hasParentCon)
                        return;
                    Console.WriteLine(Resources.MsgHintPressKey);
                    Console.ReadKey();
                    return;
                }
                foreach (var arg in args)
                {
                    if (arg.StartsWith("/"))
                    {
                        if (arg.Length < 4)
                            continue;
                        try
                        {
                            switch (arg.ToUpper().Substring(0, 3))
                            {
                                case "/A=":
                                    if (!string.IsNullOrEmpty(_argument))
                                        continue;
                                    _argument = arg.Substring(3);
                                    if (!_argument.Contains("\"{0}\\*\"") && _argument.Contains("{0}\\*"))
                                        _argument = _argument.Replace("{0}\\*", "\"{0}\\*\"");
                                    if (!_argument.Contains("\"{0}") && _argument.Contains("{0}"))
                                        _argument = _argument.Replace("{0}", "\"{0}\"");
                                    _argument = string.Format(Resources.MsgHintStartingSep, _argument);
                                    break;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Write(ex);
                        }
                        continue;
                    }
                    SetOwner(arg);
                }
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(Resources.MsgHintCompleted);
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.White;
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex);
                Console.WriteLine();
            }
            if (hasParentCon)
            {
                Console.ResetColor();
                return;
            }
            Console.WriteLine(Resources.MsgHintPressKey);
            Console.ReadKey();
        }

        private static void SetOwner(string arg)
        {
            Console.ForegroundColor = ConsoleColor.Magenta;
            if (!PathEx.DirOrFileExists(arg))
                return;
            FileAttributes fAttrib;
            try
            {
                fAttrib = File.GetAttributes(arg);
            }
            catch
            {
                fAttrib = FileAttributes.Normal;
            }
            var isDir = (fAttrib & FileAttributes.Directory) == FileAttributes.Directory;
            Console.WriteLine(Resources.MsgHintProcessing, arg);
            var command = string.Format(Resources.CmdMain, arg, isDir ? " /R" : "", string.Format(_argument.Contains("\\*") && !isDir ? _argument.Replace("\\*", string.Empty) : _argument, arg));
            Console.WriteLine(Resources.MsgHintStarting, command);
            Console.ForegroundColor = ConsoleColor.Cyan;
            using (var p = ProcessEx.Send(command, ProcessWindowStyle.Normal, false))
                if (p?.HasExited == false)
                    p.WaitForExit();
        }
    }
}
