using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using System.Linq;
using ScrambleKit.FX;

public class Exit : MonoBehaviour 
{
    public string RoomToLoad = "RoomDark";

    public Transform Doors;
    public Sprite ClosedDoorSprite;
    public int ClosedDoorLayer;
    public float GatherSpeed;

    public FXTrigger ButtonPushFX;
    public FXTrigger DoorCloseFX;

    public static bool ExitClosed;

    private SpriteRenderer doorRend;
    private List<Transform> savedHumans;
    private bool activated;
    
    void Start()
    {
        ExitClosed = false;
        doorRend = Doors.GetComponent<SpriteRenderer>();
    }

    void Update()
    {
        if (!activated)
            return;

        PullInHumans();
    }

    private void PullInHumans()
    {
        foreach (Transform t in savedHumans)
        {
            Vector3 delta = (transform.position - t.position);
            t.position += delta.normalized * GatherSpeed * Time.deltaTime;
        }
    }

    public void Activate()
    {
        activated = true;
        ExitClosed = true;

        FindHumans();
        Debug.Log("The Exit was Activated!  Found " + savedHumans.Count + " humans to save");

        ButtonPushFX.Trigger(transform);
        Invoke("CloseDoors", 1f);
        Invoke("EndLevel", 2f);
    }

    private void FindHumans()
    {
        Vector2 p = transform.position;
        Collider2D[] found = Physics2D.OverlapAreaAll(new Vector2(-3, -3) + p, new Vector2(3, 3) + p);
        savedHumans = found.Select(col => col.transform).Where(t => t.gameObject.tag == "Human").ToList();
    }

    private void CloseDoors()
    {
        doorRend.sprite = ClosedDoorSprite;
        doorRend.sortingOrder = ClosedDoorLayer;
        DoorCloseFX.Trigger(transform);
    }

    private void EndLevel()
    {
        HumanControl.EndLevelWith(savedHumans);

        if(RoomToLoad == "RoomDark" && Score.Depth >= 8)
            SceneManager.LoadScene("RoomBeforeVictory");
        else
            SceneManager.LoadScene(RoomToLoad);
    }
}
