// dotnet publish BmsTunnel.csproj -c Release -r linux-arm -p:PublishSingleFile=true --self-contained true && \
// rsync -av bin/Release/net6.0/linux-arm/publish/ root@10.2.1.6:/home/root/tunnel && clear && \
// ssh root@10.2.1.6 /home/root/tunnel/BmsTunnel

using InnovEnergy.Lib.Utils;
using static System.String;

namespace InnovEnergy.App.BmsTunnel;

public static class Program
{
    private const Byte DefaultNode = 2;

    public static async Task<Int32> Main(String[] args)
    {
        var tty = await BatteryTty.GetTty();

        if (tty is null)
            return 2;
        
        Console.WriteLine("\nstarting BMS tunnel\n");
        
        using var tunnel = new BmsTunnel(tty, 2);

        ExplainNode();
        ExplainExit();
        
        //Console.WriteLine("");

        while (true)
        {
            //Console.WriteLine("");
            Console.Write($"node{tunnel.Node}> ");

            var cmd = Console.ReadLine()?.ToUpper().Trim();

            if (IsNullOrEmpty(cmd))
                continue;

            if (cmd.StartsWith("/"))
            {
                var exit = ProcessLocalCommand(cmd);
                if (exit)
                    break;
                continue;
            }

            tunnel.SendCommand(cmd).Skip(1).ForEach(Console.WriteLine);
        }
        
        
        Boolean ProcessLocalCommand(String cmd)
        {
            cmd = cmd.TrimStart('/').Trim().ToUpper();
            
            if (cmd == "EXIT") 
                return true;
            if (cmd.StartsWith("NODE ")) 
                ChangeNode(cmd);
            else 
                Console.WriteLine("unrecognized command");

            return false;
        }

        return 0;
        

        void ChangeNode(String cmd)
        {
            var ndStr = cmd[5..].Trim();
            
            if (!Byte.TryParse(ndStr, out var newNode))
            {
                ExplainNode();
                return;
            }

            tunnel.Node = newNode;
        }
    }

    private static void ExplainExit()  => Console.WriteLine("/exit       exit bms cli");
    private static void ExplainNode()  => Console.WriteLine("/node <nb>  change to node number <nb>");
}