using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace IndianHealthService.BMXNet.WinForm.Configuration
{
    internal class CommandLineArguments
    {
        //command line, no forward slashes in value  /flag /key:value /key:"two part value"
        public Settings ParseSlashKeyValue(String[] arguments, bool ignoreErrors)
        {
            Settings answer = new Settings();
            foreach (String each in arguments)
            {
                String toParse = each;               
                try
                {
                    if (!each.EndsWith(".exe"))
                    {
                        if (toParse.StartsWith(@"""") && toParse.EndsWith(@""""))
                        {
                            toParse = toParse.Substring(1, toParse.Length - 2);
                        }
                        String[] peices = toParse.Split(new char[] { ':' });
                        String key = null;
                        String value = null;
                        if (peices.Length > 0)
                        {
                            key = peices[0];
                            if (key.StartsWith(@"/"))
                            {
                                key = key.Substring(1, key.Length - 1);
                            }

                            if (peices.Length == 1)
                            {
                                value = "true";
                            }
                            else if (peices.Length == 2)
                            {
                                value = peices[1].Replace(@"""", "");
                            }
                            else
                            {
                                key = null;
                            }
                        }

                        if (key == null)
                        {
                            throw new Exception(@"Unable to find command key.");
                        }
                        else
                        {
                            answer.AddSetting(new Setting() { Name = key.Trim(), Value = value.Trim(), IsPersistent = false });
                        }
                    }
                }
                catch (Exception problem)
                {
                    if (!ignoreErrors)
                    {
                        throw new Exception(@"Unable to parse command-line arguments.  Valid format is /flag /key:value /key:""two part value"", no forward slashes allowed", problem);
                    }
                }
            }

            return answer;
        }
    }
}