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

public class EnemyScript : MonoBehaviour
{
    public Transform bomb;

    float timer = 0f, shottimer = 0f;
    Vector3 targetpoint;
    bool falling = false;
    float fallvel;
    float lastxvel;
    bool stuck;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Vector3 pos = this.transform.position;

        if (falling)
        {
            timer -= Time.deltaTime;
            pos.x += lastxvel;
            if (pos.y<-0.3 && !stuck)
            {
                stuck = true;
                PlayerPrefs.SetInt("NeedThump", 1);
            }
            pos.y += fallvel;
            if (pos.y < -3.6)
            {
                pos.y = -3.6f;
                lastxvel = 0f;
            }
            fallvel -= 0.5f*Time.deltaTime;
            this.transform.position = pos;
            if (timer < 0)
            {
                falling = false;
                this.transform.rotation = Quaternion.identity;
            }
            return;
       }
        timer -= Time.deltaTime;
        if (timer < 0)
        {
            targetpoint.x = Random.Range(-5f, 5f);
            targetpoint.y = Random.Range(-2f, 3f);
            timer = Random.Range(0.5f, 3f);
        }

        pos.x += (targetpoint.x - pos.x) * Time.deltaTime;
        lastxvel = (targetpoint.x - pos.x) * Time.deltaTime;
        pos.y += (targetpoint.y - pos.y) * Time.deltaTime;
        this.transform.position = pos;

        shottimer -= Time.deltaTime;
        if (shottimer < 0) if (Random.Range(0f, 3f) < 2f * Time.deltaTime)
            {
                Instantiate(bomb, new Vector3(this.transform.position.x + Random.Range(-0.1f, 0.1f), this.transform.position.y - 0.7f, -0.5f), Quaternion.identity);
                PlayerPrefs.SetInt("NeedBomb", 1);
                shottimer = 0.3f+0.1f*PlayerPrefs.GetInt("Level");
            }


    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        // Only vulnerable to shots
        if (collision.gameObject.GetComponent<ShotScript>())
        {
            this.transform.Rotate(0, 0, Random.Range(-40f, 40f));
            falling = true;
            fallvel = 0.1f;
            timer = 3f;
            PlayerPrefs.SetInt("NeedAlienHit", 1);
            stuck = false;
        }

    }
}
