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

public class Cubehub : MonoBehaviour {
	
	public int worldSize = 2;
	public float worldRotationSpeed = 2f;
	
	[HideInInspector]
	public bool turnAroundInProgress = false;
	
	private Wrapper[] partWrapper;
	
	
	void Awake() {
		
		// reference child parts
		partWrapper = GetComponentsInChildren<Wrapper>();
	}
	
	// Use this for initialization
	void Start () {
		DeactivateAllLevelTiles(); // show level preview sprites only
	}
	
	// Update is called once per frame
	void Update () {
		
		// do nothing while space is held
		if (Input.GetKey(KeyCode.LeftControl)) return;
		
		// rotating cube part only in world mode
		if (ObjectHolder.Instance.gameState.currentGameState != GameStateEnum.world) return;
		
		
		if (Input.GetKeyDown(KeyCode.LeftArrow))
		{
			DeactivateAllLevelTiles();
			TurnHorizontal(1);
			SoundManager.Instance.Play(SoundManager.soundId.cubeTurn);
		}
		if (Input.GetKeyDown(KeyCode.RightArrow))
		{
			DeactivateAllLevelTiles();
			TurnHorizontal(-1);
			SoundManager.Instance.Play(SoundManager.soundId.cubeTurn);
		}
		if (Input.GetKeyDown(KeyCode.UpArrow))
		{
			DeactivateAllLevelTiles();
			TurnVertical(1);
			SoundManager.Instance.Play(SoundManager.soundId.cubeTurn);
		}
		if (Input.GetKeyDown(KeyCode.DownArrow))
		{
			DeactivateAllLevelTiles();
			TurnVertical(-1);
			SoundManager.Instance.Play(SoundManager.soundId.cubeTurn);
		}
	}
	
	
	
	public void TurnHorizontal(int horizDir)
	{
		if (turnAroundInProgress) return;
		turnAroundInProgress = true;
		
		int activeLevelRow = partWrapper[GetActiveLevelWrapperIndex()].row;
		
		foreach(Wrapper w in partWrapper)
		{
			// ignore same row player stands on
			if (w.row == activeLevelRow) continue;
			
			w.TurnAround(horizDir, 0);
		}
	}
	public void TurnVertical(int vertDir)
	{
		if (turnAroundInProgress) return;
		turnAroundInProgress = true;
		
		int activeLevelColumn = partWrapper[GetActiveLevelWrapperIndex()].column;
		
		foreach(Wrapper w in partWrapper)
		{
			// ignore same column player stands on
			if (w.column == activeLevelColumn) continue;
			
			w.TurnAround(0, vertDir);
		}
	}
	
	
	
	
	
	int GetActiveLevelWrapperIndex()
	{
		for(int i=0; i<partWrapper.Length; i++)
		{
			if (partWrapper[i].playerPresent) return i;
		}
		
		Debug.LogError("no level active?");
		return -1;
	}
	
	
	
	public void DeactivateAllLevelTiles()
	{
		foreach(Wrapper w in partWrapper)
		{
			w.DeactivateAllWrappedLevels();
		}
	}
	
	public void MarkAllWrappersAsPlayerNotBeingPresent()
	{
		foreach(Wrapper w in partWrapper)
		{
			w.SetPlayerNotPresent();
		}
	}
}
