using System.Collections;
using System.IO;
using System.Net.Sockets;
using UnityEngine;
using UnityEngine.UI;

/*
 * Command Sample

PASS oauth:ws3whxtr2jfnlas4zbaawn6p906ww8
NICK twiggieg
JOIN #twiggieg
PRIVMSG #twiggieg Hello~
PART #twiggieg

# Membership — Adds membership state event data. By default, we do not send this data to clients without this capability.
CAP REQ :twitch.tv/membership

# Tags — Adds IRC V3 message tags to several commands, if enabled with the commands capability.
CAP REQ :twitch.tv/tags

# Commands — Enables several Twitch-specific commands.
CAP REQ :twitch.tv/commands

 */

public class Test_ChatCommand : MonoBehaviour {

    private static string _ircUrl = "irc.chat.twitch.tv";
    private static int _ircPort = 6667;

#pragma warning disable 649 // Field '*' is never assigned to, and will always have its default value *
    [SerializeField]
    private Text _inputCommand;
#pragma warning restore 649

    private TcpClient _client;
    private StreamReader _reader;
    private StreamWriter _writer;

    // Use this for initialization
    private void Start() {
        _client = new TcpClient(_ircUrl, _ircPort);
        _reader = new StreamReader(_client.GetStream());
        _writer = new StreamWriter(_client.GetStream());
        Debug.Log("Ready");

        StartCoroutine(ReadRaw());
    }

    private void OnDestroy() {
        _client.Close();
        _reader.Close();
        _writer.Close();

        _client = null;
        _reader = null;
        _writer = null;
    }

    public void SendCommand() {
        Debug.Log(System.String.Format(" < {0}", _inputCommand.text));
        _writer.WriteLine(_inputCommand.text);
        _writer.Flush();

        _inputCommand.text = "";
    }

    private IEnumerator ReadRaw() {
        Debug.Log("Start Reading Raw Responses");
        while(_client != null && _reader != null) {
            if(_client.Available > 0) {
                string rawS = _reader.ReadLine();
                Debug.Log(System.String.Format(" > {0} ({1}s)", rawS, Time.time.ToString()));
            }
            yield return new WaitForEndOfFrame();
        }
        Debug.Log("End Reading Raw Responses");
    }

    // TODO: Add some HotKeys
}
