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

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

            [Option('m', Default = null,
                HelpText = "-m <status>\n" +
                " 		0 --> turn off\n" +
                "		1 --> turn on\n"
                )]
            public int? Mode { get; set; }

            [Usage(ApplicationAlias = "mx-relay-ctl")]
            public static IEnumerable<Example> Examples
            {
                get
                {
                    yield return new Example("Get value from relay index 1", new Options { RelayIndex = 1 });
                    yield return new Example("Turn on relay index 2", new Options { RelayIndex = 2, Mode = 1 });
                }
            }
        }

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

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

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

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

        private static void SetModeAction(Options opts)
        {
            Action_Struct action;
            action.index = (int)opts.RelayIndex;
            if (SetRelayData(action.index, (int)opts.Mode) < 0)
            {
                Console.WriteLine("Failed to set Relay index {0} value.", action.index);
            }
            else
            {
                action.mode = GetRelayData(action.index);
                if (action.mode >= 0)
                {
                    Console.WriteLine("Relay index {0} data: {1}", action.index, action.mode);
                }
            }
        }

        private static void GetModeAction(Options opts)
        {
            Action_Struct action;
            action.index = (int)opts.RelayIndex;
            action.mode = GetRelayData(action.index);
            if (action.mode >= 0)
            {
                Console.WriteLine(string.Format("Relay index {0} data: {1}", action.index, action.mode));
            }
        }
    }
}
