using System;
using UnityEngine;
using UnityEngine.UI;

using Sfs2X.Entities.Data;

public class Starship : GameItem 
{
	public GameObject main;
	public GameObject radar;
	public ProgressBar shieldBar;
	public Text usernameTxt;
	public int userId;

	private ISFSObject _settings;
	private bool _isMine;
	private bool _doThrust;
	private int _thrusterValue;
	private int _rotatingDir;   // Set to +1 if ship is currently rotating counterclockwise, -1 if clockwise and 0 if not rotating
	private int _shield;

    public Starship() : base()
	{
		_thrusterValue = 0;
	}

	public string username
	{
		set
		{
			usernameTxt.text = value;
		}

		get => usernameTxt.text;
	}

	public int thrusterValue
	{
		set
		{
			_thrusterValue = value;
		}

		get => _thrusterValue;
	}
	
	public bool doThrust
	{
		set
		{
			_doThrust = value;
			_thrusterValue = (value ? 2 : 0);

			animator.SetBool("doThrust", value);
		}

		get => _doThrust;
	}
	
	public float rotation
	{
		set
		{
			main.transform.eulerAngles = new Vector3 (0,0,(value * 180 / Mathf.PI)%360);
		}

		get => main.transform.rotation.eulerAngles.z * Mathf.PI / 180;
	}
	
	public int rotatingDir
	{
		set
		{
			_rotatingDir = value;
		}

		get => _rotatingDir;
	}

	public int shield
	{
		set
		{
			_shield = value;

			shieldBar.SetFill(value, _settings.GetInt("maxShield"));
		}

		get => _shield;
	}

	public bool isMine
	{
		get => _isMine;
	}

	// Thrust accceleration is converted from pixels/sec2 to pixels/ms2
	public float thrustAcceleration => (float) _settings.GetInt("thrustAccel") / 1000000f;

	// Speed is converted from pixels/sec to pixels/ms
	public float maxSpeed => ((float) _settings.GetInt("maxSpeed")) / 1000f;
	
	public float rotationSpeed => ((float) _settings.GetInt("rotationSpeed") * Mathf.PI / 180f) / 1000f;

	override protected void Update()
	{
		base.Update();

		// Set radar rotation to point the level center
		if (_isMine)
			RotateRadar();
	}

	public void Configure(ISFSObject settings, Boolean isMine)
    {
		_settings = settings;
		_isMine = isMine;

		// Hide radar
		radar.SetActive(isMine);
	}

	override public void Explode()
	{
		// Hide UI
		radar.SetActive(false);
		shieldBar.gameObject.SetActive(false);
		usernameTxt.gameObject.SetActive(false);

		// Show explosion animation
		base.Explode();
	}

	private void RotateRadar()
    {
		Vector3 target = new Vector3(0, 0, 0);
		Vector3 direction = target - radar.transform.position;
		float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
		radar.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
	}
}
