using System.Collections;
using System.Collections.Generic;
using FishNet.Object;
using TMPro;
using UnityEngine;

namespace _PROJECT.Components.Mole
{
    public class WhackAMoleMachine : NetworkBehaviour
    {
        public int score;
        public TMP_Text scoreText;
        public TMP_Text timerText;

        public float moleDistance = 0.5f;
        public float moleAppearTime = 1.5f;
        public float moleDisappearTime = 0.5f;
        public float gameLength = 60f;
        public List<Mole> moles;
        private bool _gameStarted;
        
        public void SendStartGameRPC()
        {
            StartGameRPC();
        }
        
        [ServerRpc(RequireOwnership = false)]
        private void StartGameRPC()
        {
            if (!IsServer) return;
            if (_gameStarted) return;
            _gameStarted = true;
            score = 0;
            SetScoreRPC(score);
            SetTimerRPC(gameLength);
            StartCoroutine(RunTimer());
            StartCoroutine(RiseMoles());
        }

        IEnumerator RiseMoles()
        {
            float minDelay = 0.5f;
            float maxDelay = 2f;
            float delay;
            for (float timer = 0f; timer < gameLength; timer += delay)
            {
                int randomIndex = Random.Range(0, moles.Count);
                Mole mole = moles[randomIndex];
                mole.Rise(moleDistance, moleAppearTime, moleDisappearTime, this);
                delay = Random.Range(minDelay, maxDelay);
                yield return new WaitForSeconds(delay);
            }
        }
        
        IEnumerator RunTimer()
        {
            for (float timer = gameLength; timer >= 0; timer -= Time.deltaTime)
            {
                SetTimerRPC(Mathf.FloorToInt(timer));
                yield return null;
            }

            GameOver();
        }


        public void MoleHit()
        {
            if (!IsServer) return;
            score++;
            SetScoreRPC(score);
        }
        
        [ObserversRpc]
        public void SetScoreRPC(int score)
        {
            scoreText.text = "Score: " + score;
        }
        
        [ObserversRpc]
        public void SetTimerRPC(float time)
        {
            timerText.text = "Time: " + time;
        }

        public void GameOver()
        {
            SetTimerRPC(0);
        }
    }
}