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

public class ResourceSpawner : MonoBehaviour
{

    public GameObject Level;
    public GameObject PlayerCapsule;
    public List<GameObject> ResourcePrefabs;
    public List<float> ResourceOffsets;
    public int Interval;

    [HideInInspector]
    public SpawnData[] BiomeData = new SpawnData[Global.BIOME_COUNT];

    private float counter = 0;

    void Start()
    {
        for (var i = 0; i < BiomeData.Length; i++)
            BiomeData[i] = new();
        
        BiomeData[Global.BIOME_GRASS].Add(Global.RESOURCE_TREE_BIRCH, 40000, 1000);
        BiomeData[Global.BIOME_GRASS].Add(Global.RESOURCE_TREE_SHRUB, 40000, 0);
        BiomeData[Global.BIOME_GRASS].Add(Global.RESOURCE_ORE_COPPER, 10000, 100);
        BiomeData[Global.BIOME_GRASS].Add(Global.RESOURCE_ORE_IRON, 1000, 150);
        BiomeData[Global.BIOME_GRASS].Add(Global.RESOURCE_ORE_GOLD, 100, 200);
        BiomeData[Global.BIOME_GRASS].Add(Global.RESOURCE_ORE_TITANIUM, 0, 250);
        BiomeData[Global.BIOME_GRASS].Add(Global.RESOURCE_STONE, 10000, 0);
        BiomeData[Global.BIOME_GRASS].Add(Global.RESOURCE_BEET, 20000, 1000);

        BiomeData[Global.BIOME_DIRT].Add(Global.RESOURCE_TREE_BIRCH, 200, 100);
        BiomeData[Global.BIOME_DIRT].Add(Global.RESOURCE_TREE_SHRUB, 200, 0);
        BiomeData[Global.BIOME_DIRT].Add(Global.RESOURCE_ORE_COPPER, 10000, 100);
        BiomeData[Global.BIOME_DIRT].Add(Global.RESOURCE_ORE_IRON, 1000, 150);
        BiomeData[Global.BIOME_DIRT].Add(Global.RESOURCE_ORE_GOLD, 100, 200);
        BiomeData[Global.BIOME_DIRT].Add(Global.RESOURCE_ORE_TITANIUM, 0, 250);
        BiomeData[Global.BIOME_DIRT].Add(Global.RESOURCE_STONE, 100000, 0);
        BiomeData[Global.BIOME_DIRT].Add(Global.RESOURCE_BEET, 200, 50);
    }


    void Update()
    {
        counter += Time.deltaTime;
        while (counter >= Interval)
        {
            counter -= Interval;
            Spawn();
        }
    }

    private void Spawn()
    {
        foreach (Transform child in Level.transform)
        {
            var index = Global.PositionToIndex(child.transform.position);
            var tile = Level.GetComponent<Level>().Matrix.Get(index.Identifier);
            SpawnOnTile(tile, 1);
        }
    }

    public void SpawnOnTile(Tile tile, int count)
    {
        for (var i = 0; i < count; i++)
        {
            if (tile.Nodes.Count >= Global.NODE_MAX_COUNT)
                return;
            var resourceID = BiomeData[tile.Element.GetComponent<Biome>().BiomeID].Generate(tile.Upgrade);
            var prefab = ResourcePrefabs[resourceID];
            var child = Instantiate(prefab, Global.GetRandomPositionOnTile(tile, ResourceOffsets[resourceID]), Quaternion.Euler(0, Random.Range(0, 360), 0), tile.Element);
            tile.Nodes.Add(child);
        }
    }

}
