using UnityEngine;
using System.Collections;


[RequireComponent(typeof(Tank))]
public class AITankController : MonoBehaviour {

    private Tank _tank;
    private float _lastThinkTime;
    private GameModel _model;
    private Transform _transform;
    private float _targetTurrelAngle = 0;
    private float _targetBaseAngle = 0;
    private float _speed = 0.7f;
    private bool _firstUpdate = true;
    [SerializeField] private float _thinkTime = 2f;
    [SerializeField] private float _thinkFactor = 0.6f;
    [SerializeField] private float _rotateFactor = 0.3f;

    void Start()
    {
        _tank = GetComponent<Tank>();
        _tank.fraction = 0;

        _model = FindObjectOfType(typeof(GameModel)) as GameModel;
        _model.RegisterTank(_tank);

        _transform = transform;
    }

    void Update()
    {
        _tank.Shoot();
    }

    void FixedUpdate()
    {
        if ((Time.time - _lastThinkTime > _thinkTime) || (_firstUpdate))
        {
          if ((Random.value > _thinkFactor) || (_firstUpdate))
          {
            Vector3 target; 
            var postion = _transform.position;

            if ((_model.player.transform.position - postion).magnitude < (_model.transform.position - postion).magnitude)
            {
                target = _model.player.transform.position;
            }
            else
            {
                target = _model.IGDCBase.transform.position;
            }

            // p := Game.Map.Player[0].Tank.Pos
            //else
            // p := Game.Map.Base.Pos;
            _targetTurrelAngle = -90.0f + Mathf.Atan2(target.x - postion.x, target.z - postion.z) * Mathf.Rad2Deg;

            if ((Random.value > _rotateFactor) || (_firstUpdate))
                _targetBaseAngle = _targetTurrelAngle + Random.value * 90 - 45;

            _speed = 0.7f + Random.value * 0.3f;
            //if Random < AI_DIFICULTY then
            // Fire(Pos + Vec3f(0, 2.5, 0), Angle.z - Angle.y + pi, wtShot);
            _firstUpdate = false;
          }

          _lastThinkTime = Time.time;
        }


       _tank.RotateTover(_targetTurrelAngle, Time.fixedDeltaTime);
       _tank.Move(new Vector2((Mathf.MoveTowardsAngle(_transform.rotation.eulerAngles.y, _targetBaseAngle, 10f) - _transform.rotation.eulerAngles.y) / 10.0f, _speed), Time.fixedDeltaTime);
    }

    void OnDestroy()
    {
        GameModel model = FindObjectOfType(typeof(GameModel)) as GameModel;
        if (model)
            model.UnRegister(_tank);
    }
}
