using UnityEngine;
using System.Collections;

public class RotateSky : MonoBehaviour {

	public float rotateSpeed = 50.0f;
	public int rotationDirection = -1; // -1 for clockwise
	//  1 for anti-clockwise
	
	public int rotationStep = 5;    // should be less than 90
	public GameObject[] objectsArray;
	
	private Vector3 currentRotation, targetRotation;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetMouseButtonDown (0)) {
			CheckSky ();
		}
	}
	
	private void CheckSky()
	{
		string myTag = gameObject.transform.name; //Object must have a tag in the inspector
		RaycastHit hit;
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		if (Physics.Raycast (ray, out hit)) {
			string hitTag = hit.transform.name;	
			if (hitTag == myTag) {
				currentRotation = gameObject.transform.eulerAngles;
				targetRotation.z = (currentRotation.z + (90 * rotationDirection));
				StartCoroutine (objectRotationAnimation());

			}
		}
	}
	IEnumerator objectRotationAnimation()
	{
		// add rotation step to current rotation.
		currentRotation.z += (rotationStep * rotationDirection);
		gameObject.transform.eulerAngles = currentRotation;
		
		yield return new WaitForSeconds (0);
		
		if (((int)currentRotation.z >
		     (int)targetRotation.z && rotationDirection < 0)  ||  // for clockwise
		    ((int)currentRotation.z <  (int)targetRotation.z && rotationDirection > 0)) // for anti-clockwise
		{
			StartCoroutine (objectRotationAnimation());
		}
		else
		{
			gameObject.transform.eulerAngles = targetRotation;
		}
	}
	IEnumerator rotateObjectAgain()
	{
		yield return new WaitForSeconds (0.2f);
		CheckSky();
	}
}
