using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using UnityEngine;
using Valve.VR;


public class MirrorMovement : MonoBehaviour {

	public enum Direc
	{
		X,
		Y,
		Z
	}

	public int EnhanceAmount = 0;
	public float TurnTime = 0.5f;
	public int LowestStep = -4;
	public int HighestStep = 4;
	public float StepAngle = 22.5f;
	public Direc Direction = Direc.Y;

	private int _targetStep = 0;
	private float _timer = 0;
	private Vector3 angleDirection;
	private int _maxSteps;
	private float _maxTimer;
	private Vector3 _lowestAngle;
	private Vector3 _highestAngle;

	// Use this for initialization
	void Start ()
	{
		_maxSteps = HighestStep - LowestStep;
		_targetStep = _maxSteps - HighestStep;
		_timer = _targetStep * TurnTime;
		_maxTimer = _maxSteps * TurnTime;

		switch (Direction)
		{
			case Direc.X:
				angleDirection = new Vector3(StepAngle, 0, 0);
				break;
			case Direc.Y:
				angleDirection = new Vector3(0, StepAngle, 0);
				break;
			case Direc.Z:
				angleDirection = new Vector3(0, 0, StepAngle);
				break;
		}

		Vector3 basicAngle = transform.eulerAngles;
		_lowestAngle = basicAngle + angleDirection * LowestStep;
		_highestAngle = basicAngle + angleDirection * HighestStep;

		gameObject.layer = LayerMask.NameToLayer("Mirror");

	    if (EnhanceAmount < 0)
	    {

	        GetComponentInChildren<Renderer>().material.color = Color.blue;
	    }
	    if (EnhanceAmount > 0)
	    {
	        GetComponentInChildren<Renderer>().material.color = Color.red;
	    }
	}
	
	// Update is called once per frame
	void Update ()
	{
		if(Input.GetKeyDown(KeyCode.K))
			TurnBackward();
		if (Input.GetKeyDown(KeyCode.L))
			TurnForward();

		float targetTime = _targetStep * TurnTime;
		if (Math.Abs(_timer - targetTime) < 0.0001f)
			return;
		if (_timer < targetTime)
		{
			_timer += Time.deltaTime;
			if (_timer >= targetTime)
				_timer = targetTime;
		}
		else if (_timer > targetTime)
		{
			_timer -= Time.deltaTime;
			if (_timer <= targetTime)
				_timer = targetTime;
		}

		float ratio = _timer / _maxTimer;
		transform.eulerAngles = Vector3.Lerp(_lowestAngle, _highestAngle, ratio);


	}

	public void TurnForward()
	{
		if (_targetStep < _maxSteps)
			_targetStep++;
	}

	public void TurnBackward()
	{
		if(_targetStep > 0)
			_targetStep--;
	}
}
