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

public class ConversationManager : MonoBehaviour {

	static ConversationManager __self;

	Text target;
	GameObject upArrow;
	GameObject downArrow;
	GameObject endInd;
	string planet;
	string[] conv;
	int curConv;

	public static Action atConvEnd;

	// Use this for initialization
	void Start () {
		__self = this;
	}

	void Update(){
		if(target == null)
			return;
		if(conv == null || conv.Length == 0)
			return;

		if(target.transform.parent.parent.gameObject.activeSelf == false){
			return;
		}
		else{
			if(GlobalScript.orbiting == false){
				target.transform.parent.parent.gameObject.SetActive(false);
				curConv = 0;
				conv = null;
				target = null;
				return;
			}
		}

		int change = 0;
		if(Input.GetButtonDown("Vertical")){
			float vertCache = Input.GetAxis("Vertical");
			if(vertCache > 0)
				change = -1;
			else if(vertCache < 0)
				change = 1;
		}
		if(change == 0)
			return;

		curConv += change;
		if(curConv < 0){
			curConv = 0;
			return;
		}
		if(curConv == conv.Length){
			//conversation over!
			target.transform.parent.parent.gameObject.SetActive(false);
			if(atConvEnd != null){
				atConvEnd();
			}
			return;
		}
		target.text = conv[curConv];
		if(curConv == 0)
			upArrow.SetActive(false);
		else
			upArrow.SetActive(true);
		downArrow.SetActive(true);
		if(curConv == conv.Length - 1)
			endInd.SetActive(true);
		else
			endInd.SetActive(false);
	}
	
	public static void RunConversation(string p, Text t){
		
		__self.Conversation(p, t);
	}

	public void Conversation(string p, Text t){
		target = t;
		upArrow = target.transform.FindChild("Up").gameObject;
		downArrow = target.transform.FindChild("Down").gameObject;
		endInd = target.transform.FindChild("End").gameObject;
		planet = p;
		atConvEnd = null;

		conv = ConverseStates.GetConversation(planet);
		if(conv == null)
			return;
		target.transform.parent.parent.gameObject.SetActive(true);
		curConv = 0;
		target.text = conv[curConv];
		if(curConv == 0)
			upArrow.SetActive(false);
		else
			upArrow.SetActive(true);
		downArrow.SetActive(true);
		if(curConv == conv.Length - 1)
			endInd.SetActive(true);
		else
			endInd.SetActive(false);
			
	}
}
