using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;

public class ZoomWindow : MonoBehaviour
{

    public static ZoomWindow Instance;

    private bool isOpen = false;

    private float openFor = 0f;
    
    private BoxCollider2D collider;
    private Camera _camera;
    public GameObject _sprite;

    private GameObject zoomedObject;

    private void Awake()
    {
        Instance = this;
        
        _camera = Camera.main;
        collider = GetComponent<BoxCollider2D>();
    }

    // Start is called before the first frame update
    void Start()
    {
        close();
    }

    // Update is called once per frame
    void Update()
    {
        if (isOpen)
        {
            openFor += Time.deltaTime;
        }
        else
        {
            openFor = 0;
        }
        
        if (isOpen && openFor > 0.2f &&
            (Input.GetButton("Cancel") ||
             Input.GetButton("Fire1") && 
             !collider.OverlapPoint(_camera.ScreenToWorldPoint(Input.mousePosition))))
        {
            close();
        }
    }

    public void open(GameObject z)
    {
        close();
        isOpen = true;
        collider.enabled = true;
        _sprite.SetActive(true);

        zoomedObject = z;
        zoomedObject.SetActive(true);
    }
    
    public void close()
    {
        isOpen = false;
        collider.enabled = false;
        _sprite.SetActive(false);

        if (zoomedObject != null)
        {
            zoomedObject.SetActive(false);
        }

        zoomedObject = null;
    }
}
