using UnityEngine;
using System.Collections;
using System;
using System.Linq;
using Irc;

public class TwitchVoting : MonoBehaviour {

    private bool isVoting = false;
    private int[] tally;
    private string[] voteTypes;

	// Use this for initialization
	void Start () {
        // Subscribe for events
        TwitchIrc.Instance.OnChannelMessage += AddVote;
        TwitchIrc.Instance.OnServerMessage += OnServerMessage;
    }

    /**
    CLEAR VOTES
    Clears votes from the tally container.
    **/
    void ClearVotes(int length)
    {
        tally = new int[length];
        for(int i = 0; i < length; i++)
        {
            tally[i] = 0;
        }
    }

    /**
    START VOTE
    Calls clear votes and tells the class it can collect votes.
    Tells the class what votes it can collect.
    **/
    public string StartVote(string[] types)
    {
        if (!isVoting)
        {
            voteTypes = types;
            ClearVotes(voteTypes.Length);
            isVoting = true;
            return "started vote";
        }
        else
        {
            return "!already voting";
        }
    }

    /**
    STOP VOTE
    Tallys the votes and returns the winner.
    Clears the tally container.
    Tells the class to not collect votes.
    **/
    public string GetVoteResult()
    {
        if (isVoting)
        {
            string winner = TallyVotes();
            isVoting = false;
            return winner;
        }
        else
        {
            return "!no vote";
        }
    }

    public void StopVote()
    {
        isVoting = false;
    }

    /**
    TALLY VOTES
    Tallys the votes and finds the winner
    **/
    string TallyVotes()
    {
        // Get the winning val
        int maxVal = tally.Max();

        // check if there are votes in the tally
        if(maxVal == 0)
        {
            return "none";
        }

        int maxIndex = Array.IndexOf(tally, maxVal);
        return voteTypes[maxIndex];
    }

    /**
    ADD VOTE
    Takes an irc message, checks if it's valid and adds it to tally
    **/
    void AddVote(ChannelMessageEventArgs channelMessageArgs)
    {
        Debug.Log("MESSAGE: " + channelMessageArgs.From + ": " + channelMessageArgs.Message);
        string vote = channelMessageArgs.Message.ToUpper().TrimStart(':');
        if (voteTypes.Contains(vote))
        {
            int voteIndex = Array.IndexOf(voteTypes, vote);
            tally[voteIndex]++;
        }
    }

    //Receive message from server
    void OnServerMessage(string message)
    {
        Debug.Log(message);
    }
}
