﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Net.Sockets;
using System.Net;
using System.Windows.Input;
using BNEBotCore;
using System.Windows;

namespace BNEBotManager
{
  public class ApplicationContext
  {
    public ApplicationContext()
    {
      ConnectedLaunchers = new ObservableCollection<LauncherConnection>();

      // Handle command line
      CommandLine.RegisterSwitch("urls", "List of initial URLs to connect, separated by ;",
        (a) => { InitiateStartingConnections((string)a[0]); }, typeof(string));

      string[] rawArgs = Environment.GetCommandLineArgs();
      string[] args = new string[rawArgs.Length - 1];
      for (int i = 1; i < rawArgs.Length; ++i)
      {
        args[i - 1] = rawArgs[i];
      }
      CommandLine.Process(args);

      // TEMP: Always connect localhost launcher
      //InitiateLauncherConnection(IPAddress.Loopback, 6666, "localhost:6666");
    }

    public ObservableCollection<LauncherConnection> ConnectedLaunchers
    {
      get;
      set;
    }

    public ICommand OpenConnectionCommand
    {
      get
      {
        return m_OpenConnectionCommand ?? (m_OpenConnectionCommand = new CommandHandler(() => OnOpenConnection()));
      }
    }
    private ICommand m_OpenConnectionCommand;

    public void Exit()
    {
      foreach (LauncherConnection connection in ConnectedLaunchers)
      {
        connection.Close();
      }
    }

    private void OnOpenConnection()
    {
      OpenConnectionDialog dlg = new OpenConnectionDialog();
      bool? ret = dlg.ShowDialog();
      if (ret.HasValue && ret.Value)
      {
        InitiateLauncherConnection(dlg.Url, dlg.Port);
      }
    }

    // Initiate new connection
    public void InitiateLauncherConnection(IPAddress addr, int port, string name = "")
    {
      ConnectedLaunchers.Add(new LauncherConnection(addr, port));
      if (!string.IsNullOrEmpty(name))
      {
        ConnectedLaunchers.Last().ID = name;
      }
    }

    private void InitiateStartingConnections(string list)
    {
      string[] ips = list.Split(';');
      foreach (string address in ips)
      {
        string[] tokens = address.Split(':');
        if (tokens.Length == 2)
        {
          IPAddress addr;
          if (IPAddress.TryParse(tokens[0], out addr))
          {
            int port;
            if (int.TryParse(tokens[1], out port))
            {
              InitiateLauncherConnection(addr, port);
            }
          }
        }
      }
    }
  }
}
