using Cysharp.Threading.Tasks;
using Enums;
using Services;
using UnityEngine;
using Utils;

namespace Views {
    public class GemView : MonoBehaviour {
        private Gem gem;
        public Gem Gem => this.gem;

        private bool isFalling;

        public void Bind(Gem gem) {
            this.gem = gem;
            this.gameObject.SetActive(true);
        }
        
        public void Unbind() {
            this.gem = null;
            this.gameObject.SetActive(false);
            this.isFalling = false;
        }

        private async UniTask FallDelay() {
            float randomDelay = 1 * this.gem.Position.y / 100f;
            await UniTask.WaitForSeconds(randomDelay);
            this.isFalling = true;
        }
        
        public async UniTaskVoid UpdatePosition(Vector2Int positionBasedOnIndex, float gemSpeed) {
            if (!this.isFalling) {
                await FallDelay();
            }

            if (!this.isFalling)
                return;
            
            if (Vector2.Distance(this.transform.position, positionBasedOnIndex.ToVector2()) > 0.01f) {
                this.transform.position = Vector2.Lerp(this.transform.position, positionBasedOnIndex.ToVector2(), gemSpeed);
            }
        }
    }
}