using System.Collections.Generic;
using UnityEngine;
using static Extensions;

[CreateAssetMenu(menuName = "Gather And Defend/Resource Tile")]
public class ResourceTile : LevelTile
{
    [SerializeField]
    [Tooltip("the prefab of the currency that will be spawned when mining this resource")]
    private GameObject _yieldPrefab;

    private string YieldPrefabName => _yieldPrefab.name;

    [SerializeField]
    private float _yieldSpeed = 1; //resource per second
    [SerializeField]
    [Range(0.0f, 5.0f)]
    private float _randomPositionConfig = 0.5f;
    private float _yieldCounter = 0;
    public bool Occupied { get; set; }

    public override void LevelUpdate()
    {
        //if (!Occupied) return; Uncomment once tile occupation exists


        _yieldCounter += Time.deltaTime * _yieldSpeed;
        if (_yieldCounter < 1) return;

        _yieldCounter = 0;
        float rangeConfig = 0.5f + _randomPositionConfig;
        Vector3 yieldPosition = new Vector3(Position.x + Random.Range(-rangeConfig, rangeConfig), Position.y, Position.z);
        var yielded = Instantiate(_yieldPrefab, yieldPosition, Quaternion.identity);
        yielded.transform.SetParent(LevelManager.Instance.LevelTransform);
    }
    public override bool Equals(ILevelObject other)
    {
        return other is ResourceTile otherRes
            && base.Equals(otherRes)
            && _yieldPrefab == otherRes._yieldPrefab
            && _yieldSpeed == otherRes._yieldSpeed
            && Occupied == otherRes.Occupied;
    }
    public override Dictionary<string, object> ToDictionary()
    {
        var dict = base.ToDictionary();

        dict[nameof(YieldPrefabName)] = YieldPrefabName;
        dict[nameof(_yieldSpeed)] = _yieldSpeed;
        dict[nameof(Occupied)] = Occupied;
        return dict;
    }
    public override void LoadDictionary(Dictionary<string, object> dict)
    {
        base.LoadDictionary(dict);
        var prefabName = dict[nameof(YieldPrefabName)].ToString();
        _yieldPrefab = Database.Instance.Prefabs[prefabName];
        _yieldSpeed = dict[nameof(_yieldSpeed)].ToFloat();
        _yieldCounter = dict[nameof(_yieldCounter)].ToFloat();
        Occupied = dict[nameof(Occupied)].ToBool();
    }
}