using UnityEngine;
using System.Collections;

public class rotate : MonoBehaviour
{
    Transform rotator;
	public static float speed = 3.0f;
    public float halfCubeSize = 1.0f;
    public bool rotating = false;
    float posx, posy;

    void Start()
    {
        posx = 0; posy = 0;
        rotator = (new GameObject("Rotator")).transform;
    }

    bool rara = false;
    IEnumerator RotateCube(Vector3 refPoint, Vector3 rotationAxis)
    {
        if (rara)
            yield break;
        rara = true;
        rotator.localRotation = Quaternion.identity;
        rotator.position = transform.position - Vector3.up * halfCubeSize + refPoint;
        transform.parent = rotator;
        float angle = 0;

        while (angle < 90.0)
        {
            angle += Time.deltaTime * 90.0f * speed;
            if (angle > 90)
                angle = 90;
            rotator.rotation = Quaternion.AngleAxis(angle, rotationAxis);
            yield return 0;
        }
        rara = false;
        transform.parent = null;
        rotating = false;
        transform.rotation = Quaternion.Euler(Vector3.zero);
        transform.position = new Vector3(Mathf.Round(transform.position.x), Mathf.Round(transform.position.y), Mathf.Round(transform.position.z));
        Messenger<Vector2>.Broadcast("cube movement", Test.CubePos);
    }

    public static int last = 0;
    void Update()
    {
        if (Globals.IsGamePaused) return;
        //if (!rotating)
        {
            if (last == 0 || Input.GetKey(KeyCode.D) || swipe.dir == swipe.Direction.RIGHT)
            {
                last = 0;
                rotating = true;
                StartCoroutine(RotateCube(Vector3.right * halfCubeSize, -Vector3.forward));
            }
            if (last == 1 || Input.GetKey(KeyCode.A) || swipe.dir == swipe.Direction.LEFT)
            {
                last = 1;
                rotating = true;
                StartCoroutine(RotateCube(-Vector3.right * halfCubeSize, Vector3.forward));
            }
            if (last == 2 || Input.GetKey(KeyCode.W) || swipe.dir == swipe.Direction.UP)
            {
                last = 2;
                rotating = true;
                StartCoroutine(RotateCube(Vector3.forward * halfCubeSize, Vector3.right));
            }
            if (last == 3 || Input.GetKey(KeyCode.S) || swipe.dir == swipe.Direction.DOWN)
            {
                last = 3;
                rotating = true;
                StartCoroutine(RotateCube(-Vector3.forward * halfCubeSize, -Vector3.right));
            }
        }
    }
}