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

public class Door : MonoBehaviour
{
    [SerializeField] private string _room;
    [SerializeField] private GameObject _player;
    [SerializeField] private string _position = "";
    [SerializeField] private GameObject _playerSpawnPosition;
    private bool _isPlayerHere = false;
    private bool _positioned = false;
    private GameObject spawn;
    // Start is called before the first frame update
    void Start()
    {
        
        if(_position == ""){
            SpawnPlayer();
        }
    }

    // Update is called once per frame
    void Update()
    {
        if(_isPlayerHere && Input.GetKeyDown(KeyCode.Space)){
            SceneManager.LoadScene(_room);
            SpawnPlayer();
        }

        if (spawn == null && _position != ""){
            spawn = GameObject.FindGameObjectWithTag(_position + "Spawn");
        }

        if(spawn != null & !_positioned){
            _positioned = true;
            this.transform.position = spawn.transform.position;
            SpawnPlayer();
        }
    }

    private void OnTriggerEnter2D(Collider2D other) {
        if(other.tag == "Player"){
            //_isPlayerHere = true;
            SceneManager.LoadScene(_room);
            SpawnPlayer();
        }
    }

    private void OnTriggerExit2D(Collider2D other) {
        if(other.tag == "Player"){
            _isPlayerHere = false;
        }
    }

    void SpawnPlayer(){
        if(RoomManager.currentRoom == _room)
        {
            Instantiate(_player, _playerSpawnPosition.transform.position, Quaternion.identity);
            Scene currentScene = SceneManager.GetActiveScene();
            RoomManager.currentRoom = currentScene.name;
        }
    }
}
