using System;
using UniRx;
using UnityEngine;
using Random = UnityEngine.Random;

namespace Nan.Scripts
{
    public class Enemy : MonoBehaviour
    {
        private readonly EnemyStatus _enemyStatus = new EnemyStatus {Attack = 0, Defence = 0, Hp = 1};
        [SerializeField] private GameObject _bomb;
        [SerializeField] private SpriteRenderer _spriteRenderer;

        private readonly Subject<Unit> _died = new Subject<Unit>();

        public PlayerControl PlayerControl { get; set; }
        public IObservable<Unit> OnDied { get { return _died; } }

        private float _flushTime;

        public void Start()
        {
            _enemyStatus.Hp = 1;
            _flushTime = Random.Range(0, 1.0f);
        }

        public void Update()
        {
            _flushTime -= Time.deltaTime * 4;
            _spriteRenderer.color = Color.Lerp(Color.white, Color.red, Mathf.Clamp01(_flushTime));
        }

        private void OnCollisionEnter2D(Collision2D other)
        {
            if (other.gameObject.GetComponent<PlayerBullet>() == null) return;
            _enemyStatus.Hp -= 0.4f;
            _flushTime = 1;
            Debug.Log(_enemyStatus.Hp);

            if (!(_enemyStatus.Hp < 0)) return;
            
            var pos = transform.position;
            var bomb = Instantiate(_bomb);
            bomb.transform.position = pos;

            ScoreManager.Instance.AddScore(500, transform.position);
            Destroy(gameObject);
        }
    }
}
