using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DoorController : MonoBehaviour
{
    // Start is called before the first frame update
    public Collider2D bluePlayerCollider;
    public Collider2D orangePlayerCollider;
    public Animator doorAnimator;

    public Animator buttonBlue;
    public Animator buttonOrange;

    private Collider2D doorCollider;

    // Dodělat manuálně se připíše level number 
    //public int levelNumber;

    private void Awake()
    {
        doorCollider = GetComponent<BoxCollider2D>();
    }

    private void Update()
    {
        if (buttonBlue.GetBool("ButtonPressed") && buttonOrange.GetBool("ButtonPressed"))
            doorAnimator.SetBool("DoorOpen", true);
        if (doorAnimator.GetBool("DoorOpen") && doorCollider.IsTouching(bluePlayerCollider) && doorCollider.IsTouching(orangePlayerCollider))
        {
            int index = levelChooser.GetIndex();
            LoadChangeSaveLevels(index);
            levelChooser.NextLevel();
        }
    }

    private void LoadChangeSaveLevels(int index) 
    {
        Levels levels =  new Levels(SaveSystem.LoadLevels());
        if (index < 15)
        {
            if (LookForCollectable())
                levels.ChangeShipProgress(index, 2);
            else
                levels.ChangeShipProgress(index, 3);
            if (index < 14)
            {
                if (levels.GetShipProgressOnIndex(index + 1) == 0)
                    levels.ChangeShipProgress(index + 1, 1);
            }
            else {
                if (levels.GetMoonProgressOnIndex(0) == 0)
                    levels.ChangeMoonProgress(0, 1);
            }
        }
        else if (index >= 15 && index < 30) 
        {
            index = index - 15;
            if (LookForCollectable())
                levels.ChangeMoonProgress(index, 2);
            else
                levels.ChangeMoonProgress(index, 3);
            if (index < 14) {
                if (levels.GetMoonProgressOnIndex(index + 1) == 0)
                    levels.ChangeMoonProgress(index + 1, 1);
            }
        }

        SaveSystem.SaveLevels(levels);
    }

    private bool LookForCollectable() 
    {
        if (GameObject.FindWithTag("Collectable") is null)
            return false;
        return true;
    }
}
