using System;
using Patterns_And_Principles.Patterns.The_Observer_Pattern.WithoutEvent.Script._02_RealWorldUsage.Observer;
using UnityEngine;

namespace Patterns_And_Principles.Patterns.The_Observer_Pattern.WithoutEvent.Script._02_RealWorldUsage.Subject
{
    public class BikeController : Abstract.Subject
    {
        public bool IsTurboOn { get; private set; }

        public float CurrentHealth
        {
            get { return health; }
        }

        private bool _isEngineOn;
        private HUDContoller _hudContoller;
        private CameraController _cameraController;

        [SerializeField]
        private float health;

        private void OnEnable()
        {
            if (_hudContoller)
            {
                Attach(_hudContoller);
            }

            if (_cameraController)
            {
                Attach(_cameraController);
            }
        }

        private void OnDisable()
        {
            if (_hudContoller)
            {
                Detach(_hudContoller);
            }

            if (_cameraController)
            {
                Detach(_cameraController);
            }
        }

        private void Awake()
        {
            _hudContoller = gameObject.AddComponent<HUDContoller>();
            _cameraController = (CameraController)FindObjectOfType(typeof(CameraController));
        }

        private void Start()
        {
            StartEngine();
        }

        private void StartEngine()
        {
            _isEngineOn = true;
            NotifyObservers();
        }

        public void ToggleTurbo()
        {
            if (_isEngineOn)
            {
                IsTurboOn = !IsTurboOn;
            }

            NotifyObservers();
        }

        public void TakeDamage(float amount)
        {
            health -= amount;
            IsTurboOn = false;
            NotifyObservers();
            if (health <= 0)
            {
                Destroy(gameObject);
            }
        }
    }
}