using System.Collections;
using UnityEngine;

namespace Subworlds.Scripts
{
  class BrokenTurretScript : EnemyScript
  {
    private Vector3 dir;
    private bool attacking;

    private void Awake()
    {
      trig[0] = gameObject.transform.GetChild(1).gameObject;
      trig[1] = gameObject.transform.GetChild(2).gameObject;
      Initialize(130, 7, 80, new int[] { 25, 25, 52 }, 60);

      var network = gameObject.GetComponent<NetworkEnemyBasic>();
      network.isPirate = true;

      canKnockback = false;
    }

    private void Update()
    {
      if (Network.isServer)
      {
        if (!attacking)
        {
          if (target)
          {
            if (Mathf.Abs(target.transform.position.x - t.position.x) < 45f)
            {
              attacking = true;
              StartCoroutine(Attack());
            }
            else
            {
              target = null;
            }
          }
        }
      }
    }

    private int z = 0;

    private IEnumerator Seach(int count)
    {
      for (int i = 0; i < count; i++)
      {
        dir = target.transform.position - t.position;
        dir.Normalize();
        var newRotation = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        var diffAngle = (z - newRotation + 180) % 360 - 180;

        z = (int)(z - diffAngle / 6f);

        z = (z + 360) % 360;

        gameObject.transform.GetChild(0).GetChild(0).GetChild(0).localEulerAngles = new Vector3(0, ((z + 360 - 90) % 360) > 180 ? 0 : 180, ((z + 360 - 90) % 360) > 180 ? z : 180 - z);

        yield return new WaitForSeconds(0.01f);
      }
    }

    private IEnumerator Attack()
    {
      yield return Seach(Random.Range(0, 100));


      for (int i = 0; i < 3; i++)
      {
        dir = target.transform.position - t.position;
        dir.Normalize();
        var newRotation = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        z = (int) newRotation;
        z = (z + 360) % 360;
        gameObject.transform.GetChild(0).GetChild(0).GetChild(0).localEulerAngles = new Vector3(0, ((z + 360 - 90) % 360) > 180 ? 0 : 180, ((z + 360 - 90) % 360) > 180 ? z : 180 - z);
        var pos = target.transform.position;
        var dist = 2.1f;
        var endPosition = new Vector3(t.position.x + Mathf.Cos((Mathf.PI / 180) * z) * dist, t.position.y + Mathf.Sin((Mathf.PI / 180) * z) * dist, t.position.z);
        var p = (GameObject)Network.Instantiate(Resources.Load("proj/pirateproj"), endPosition, Quaternion.identity, 0);
        p.SendMessage("EnemySet", pos, SendMessageOptions.DontRequireReceiver);
        yield return new WaitForSeconds(1.625f);
        yield return Seach(10);
      }

      yield return Seach(200 + Random.Range(0, 200));

      attacking = false;
      yield break;
    }
  }
}