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

public class AntennaHandler : MonoBehaviour {

	public enum EnLight
	{
		Red,
		Orange,
		Green
	}

    private Transform targetAntenna;
    private Transform targetPortal;
    private Transform portal;
	private Transform player;
	public EnLight color;
	public Light light;
	public Image signal;
	public Image compass;
	private float _speed = 10.0f;
	float distance = 26.0f;
	bool shouldBlink = true;

    private GameController controller;

	public void Init(GameController controller)
    {
        this.controller = controller;
        light.range = 0.6f;

        compass = controller.UIController.GameplayView.Compass;
        signal = controller.UIController.GameplayView.Singal;
        player = controller.Player.transform;
        portal = controller.MapPortal.transform;
        targetAntenna = MapManager.GetTileSafe (controller.MapController.MapInstance.Tiles, controller.MapController.MapInstance.wifiPlacePointX, controller.MapController.MapInstance.wifiPlacePointX).transform;
        targetPortal = MapManager.GetTileSafe (controller.MapController.MapInstance.Tiles, controller.MapController.MapInstance.endPointX, controller.MapController.MapInstance.endPointY).transform;
	}

	private void Update () {

		if (targetAntenna == null || signal == null || player == null)
			return;
			
        distance = Mathf.Abs (Vector2.Distance (new Vector2 (targetAntenna.position.x, targetAntenna.position.z), new Vector2 (transform.position.x, transform.position.z)));

        this.controller.MapPortal.DisablePortal();
		if (distance < 2.0f) {
            this.controller.MapPortal.EnablePortal();
			color = EnLight.Green;
			shouldBlink = false;
			light.intensity = 30.0f;
			signal.fillAmount = 1.0f;
		} else if (distance > 1.0f && distance < 10.0f) {
			color = EnLight.Green;
			shouldBlink = true;
			signal.fillAmount = 0.8f;
		} else if (distance > 10.0f && distance < 25.0f) {
			color = EnLight.Orange;
			shouldBlink = true;
			signal.fillAmount = 0.6f;
		} else if (distance > 25.0f) {
			color = EnLight.Red;
			shouldBlink = true;
			signal.fillAmount = 0.4f;
		}
			
		switch (color) {
		case EnLight.Green:
			light.color = Color.green;
			break;
		case EnLight.Orange:
			light.color = new Color (1.0f, 150.0f / 255.0f, 0.0f);
			break;
		case EnLight.Red:
			light.color = Color.red;
			break;
		}

		if (shouldBlink) {
			light.intensity = Mathf.PingPong (Time.time, 1.0f) * 30.0f;
		}

        Vector3 dir;
        if (!this.transform.parent && this.portal.gameObject.activeInHierarchy) {
            dir = player.transform.position - this.targetPortal.position;
        } else {
            dir = player.transform.position - transform.position;
        }

		dir = dir.normalized;

		var angle = Vector2.SignedAngle (Vector2.up, new Vector2(dir.x, dir.z));
		compass.transform.rotation = Quaternion.Euler(0.0f, 0.0f, angle + 90.0f);
	}
}
