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

public class Spawner : MonoBehaviour {
    public string type = "player";
    public GameManager gm;
    public Vector2 offset;

    private void Start()
    {
        for(int i = 0; i < 0; i++)
        {
            spawnPrefab();
        }
    }

    public void spawnPrefab(bool clicker = false)
    {
        Vector2 v;
        if (clicker)
            v = FindPoint(true);
        else
            v = FindPoint();

        if (type == "player")
        {
            if (!clicker)
            {
                GameObject go = (Instantiate(Resources.Load("Bee"), v, Quaternion.identity)) as GameObject;
                Bee b = go.GetComponent<Bee>();
                b.Force *= (100f - (gm.Bees.Count * 3)) / 100;
                if (b.Force < 50f)
                    b.Force = 50f;

                b.VectorOffset = v;
                gm.Bees.Add(b);
                gm.pm.freeBees.Add(b);
            }
            else
            {
                GameObject go = (Instantiate(Resources.Load("Clicker"), v, Quaternion.identity)) as GameObject;
                go.transform.position = new Vector2(v.x - 3.2f, v.y);
            }
        }
        else if (type == "enemy")
        {
            GameObject go = (Instantiate(Resources.Load("Fly"), v, Quaternion.identity)) as GameObject;
            Fly f = go.GetComponent<Fly>();
            f.VectorOffset = v;
            gm.Flies.Add(f);
            gm.em.freeFlies.Add(f);
        }
    }

    Vector2 FindPoint(bool small = false)
    {
        Vector2 returnVector = new Vector2();
        int counter = 0;

        while(returnVector.x == 0)
        {
            Vector2 v;
            if (small)
                v = Random.insideUnitCircle * 1.5f;
            else
                v = Random.insideUnitCircle * 2.5f;
            v.x = v.x + offset.x;
            v.y = v.y + offset.y;

            RaycastHit2D hit = Physics2D.Raycast(v, -Vector2.up, 0.01f);

            if (hit.collider == null)
            {
                returnVector = v;
            }

            counter++;
            if (counter > 100)
            {
                break;
            }
        }

        return returnVector;
    }
}
