using System.Collections;
using Movement;
using UnityEngine;

namespace Platforms
{
    public class CollapsingPlatform : MonoBehaviour
    {
        private const float TimeBeforeCollapse = 2.0f;
        private const float TimeBeforeReset = 4.0f;

        private CollisionChecker _collidingTriggerCheck;

        public Sprite small;
        public Sprite medium;
        public Sprite large;
        public Sprite smallCollapsing;
        public Sprite mediumCollapsing;
        public Sprite largeCollapsing;

        private bool _onCollision;

        [Range(1, 3)] public int size;

        private void Awake()
        {
            _collidingTriggerCheck = GetComponentInChildren<CollisionChecker>();
        }

        private void Update()
        {
            if (!_collidingTriggerCheck.IsCollided || _onCollision) return;
            _onCollision = true;
            StartCoroutine(Collapse());
        }

        private void ChangeState(bool state)
        {
            GetComponent<SpriteRenderer>().enabled = state;
            GetComponent<Collider2D>().enabled = state;
        }

        private IEnumerator Collapse()
        {
            switch (size)
            {
                case 1:
                    GetComponent<SpriteRenderer>().sprite = smallCollapsing;
                    break;
                case 2:
                    GetComponent<SpriteRenderer>().sprite = mediumCollapsing;
                    break;
                case 3:
                    GetComponent<SpriteRenderer>().sprite = largeCollapsing;
                    break;
            }

            yield return new WaitForSeconds(TimeBeforeCollapse);
            ChangeState(false);
            StartCoroutine(Reset());
        }

        // ReSharper disable once Unity.IncorrectMethodSignature
        private IEnumerator Reset()
        {
            yield return new WaitForSeconds(TimeBeforeReset);
            _onCollision = false;
            switch (size)
            {
                case 1:
                    GetComponent<SpriteRenderer>().sprite = small;
                    break;
                case 2:
                    GetComponent<SpriteRenderer>().sprite = medium;
                    break;
                case 3:
                    GetComponent<SpriteRenderer>().sprite = large;
                    break;
            }

            ChangeState(true);
        }
    }
}