using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Machete {
	public class PlayableCheater : Cheater {
    [SerializeField]
    private int questionsAmount = 4;
    [SerializeField]
    private Message messagePrefab;
    [SerializeField]
    int attemptsPerQuestion = 2;

    delegate void TickHandler();
    TickHandler currentHandler;
    List<Cheater> receivers;
    int questionsAnswered = 0;
    int attempts;

    Message message;

    public void MessageLost() {
      message = null;
      currentHandler = CreateMessage;
      SoundManager.Instance.PlaySound("Angry");
    }


    public void MessageCaught() {
      message = null;
      attempts = 0;
      currentHandler = CreateMessage;
      SoundManager.Instance.PlaySound("Alarm");
    }

    protected override void Start() {
      base.Start();
      IsPlayable = true;
      // Create list of questions.
      receivers = new List<Cheater>();
      // Make a copy of all the cheaters but remove this.
      List<Cheater> cheaters = new List<Cheater>();
      cheaters.AddRange(grid.Cheaters);
      cheaters.Remove(this);
      // Randomly select cheaters for questioning
      for (var i = 0; i < Mathf.Min(grid.Cheaters.Count, questionsAmount); i++) {
        int random = Random.Range(0, cheaters.Count);
        receivers.Add(cheaters[random]);
        cheaters.RemoveAt(random);
      }
      // Set attempts
      attempts = attemptsPerQuestion;
      // Handle Ticker.
      ticker.OnTick += HandleTick;
      currentHandler = CreateMessage;
    }

    void HandleTick() {
      currentHandler();
    }

    void CreateMessage() {
      // Check if we need to stop trying.
      attempts--;
      if (attempts < 0) {
        attempts = attemptsPerQuestion;
        receivers.RemoveAt(0); // TODO: Notify player of lost chance.
      }
      if (receivers.Count == 0) {
        GameManager.Instance.EndGame();
        currentHandler += WaitForEnd;
      }
      // Create new message.
      message = Instantiate(messagePrefab);
      message.Sender = this;
      message.Receiver = receivers[0];
      desk.Message = message;
      currentHandler = Planning;
      this.MarkAsSender(true);
    }

    public override bool TakeMessage(Message message) {
      Destroy(message.gameObject);
      questionsAnswered++; // TODO: Inform player of success.
      GameManager.Points = questionsAnswered;
      receivers.RemoveAt(0);

      if (receivers.Count > 0) {
        attempts = attemptsPerQuestion;
        currentHandler = CreateMessage;
      } else {
        GameManager.Instance.EndGame();
        currentHandler += WaitForEnd;
      }

      return true;
    }

    void Planning() {

    }

    void WaitResponse() {

    }

    void WaitForEnd() {

    }
	}
}
