using UnityEngine;
using UnityEngine.SceneManagement;

namespace Assets.Scripts
{
    public class Player : MonoBehaviour
    {
        private Transform _pos;
        private float _blinkTimer = 0f;
        private int _blinkCount = 0;

        public int Score = 0;
        public int Battery = 100;
        public int Progression = 0;
        public bool IsBlinking = false;
        public int NbVials = 0;

        void Start()
        {
            _pos = GetComponent<Transform>();
        }

        void Update()
        {
            var newPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            newPos.z = -1;

            _pos.position = Vector3.Lerp(_pos.position, newPos, 10*Time.deltaTime);
            if (IsBlinking)
                Blink();

            if (Battery < 12)
            {
                if (PlayerPrefs.GetInt("highscore") < Score)
                    PlayerPrefs.SetInt("highscore", Score);
                SceneManager.LoadScene("GameOver");
            }
            if (Progression == 25)
            {
                if (PlayerPrefs.GetInt("highscore") < Score)
                    PlayerPrefs.SetInt("highscore", Score);
                SceneManager.LoadScene("Win");
            }
        }

        public void Blink()
        {
            _blinkTimer += Time.deltaTime;

            if (_blinkTimer > .16f)
            {
                GetComponent<SpriteRenderer>().enabled = !GetComponent<SpriteRenderer>().enabled;
                _blinkCount++;
                _blinkTimer = 0f;
            }

            if (_blinkCount != 7) return;
            _blinkCount = 0;
            _blinkTimer = 0f;
            GetComponent<BoxCollider2D>().enabled = true;
            IsBlinking = false;
        }

        public void SetBlinking()
        {
            GetComponent<BoxCollider2D>().enabled = false;
            GetComponent<SpriteRenderer>().enabled = false;
            IsBlinking = true;
        }
    }
}