using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace mx_sim_ctl
{
    class Program
    {
        class Options
        {
            [Option('i', Required = true, HelpText = "-i <#SIM port index> (Start from 0)")]
            public uint SIMPortIndex { get; set; }

            [Option('m', Default = null,
                HelpText = "-n <sim slot>\n" +
                " 		0 --> SIM slot 0\n" +
                "		1 --> SIM slot 1\n"
                )]
            public int? SIMSlot { get; set; }

            [Usage(ApplicationAlias = "mx-sim-ctl")]
            public static IEnumerable<Example> Examples
            {
                get
                {
                    yield return new Example("Get sim slot from sim port 1", new Options { SIMPortIndex = 1 });
                    yield return new Example("Set sim port 1 to sim slot 1", new Options { SIMPortIndex = 1, SIMSlot = 1 });
                }
            }
        }

        [DllImport("mxsim.dll", EntryPoint = "GetSIMSlot", CharSet = CharSet.Ansi, SetLastError = true)]
        public static extern int GetSIMSlot(int port);

        [DllImport("mxsim.dll", EntryPoint = "SetSIMSlot", CharSet = CharSet.Ansi, SetLastError = true)]
        public static extern int SetSIMSlot(int port, int mode);

        public struct Action_Struct
        {
            public int index;
            public int slot;
        };

        static void Main(string[] args)
        {
            CommandLine.Parser.Default.ParseArguments<Options>(args)
                .WithParsed(opts =>
                {
                    if (opts.SIMSlot == null)
                    {
                        GetModeAction(opts);
                    }
                    else
                    {
                        SetModeAction(opts);
                    }
                });
        }

        private static void SetModeAction(Options opts)
        {
            Action_Struct action;
            action.index = (int)opts.SIMPortIndex;
            if (SetSIMSlot(action.index, (int)opts.SIMSlot) < 0)
            {
                Console.WriteLine("Failed to set slot of SIM port {0}.", action.index);
            }
            else
            {
                action.slot = GetSIMSlot(action.index);
                if (action.slot >= 0)
                {
                    Console.WriteLine("SIM port {0} slot: {1}", action.index, action.slot);
                }
            }
        }

        private static void GetModeAction(Options opts)
        {
            Action_Struct action;
            action.index = (int)opts.SIMPortIndex;
            action.slot = GetSIMSlot(action.index);
            if (action.slot >= 0)
            {
                Console.WriteLine(string.Format("SIM port {0} slot: {1}", action.index, action.slot));
            }
        }
    }
}
