using System.Collections;
using UnityEngine;

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

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

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

    private int z = 0;

    private IEnumerator Seach(int count)
    {
      for (int i = 0; i < count; i++)
      {
        this.dir = this.target.transform.position - this.t.position;
        this.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(100 + Random.Range(0, 30));


      for (int i = 0; i < 3; i++)
      {
        this.dir = this.target.transform.position - this.t.position;
        this.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 = this.target.transform.position;
        var dist = 2.1f;
        var endPosition = new Vector3(this.t.position.x + Mathf.Cos((Mathf.PI / 180) * z) * dist, this.t.position.y + Mathf.Sin((Mathf.PI / 180) * z) * dist, this.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(0.625f);
        yield return Seach(10);
      }

      this.attacking = false;
      yield break;
    }
  }
}