using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

public class ObjectInteraction : MonoBehaviour
{
    public Image loadingImage;
    public float totalTime = 2;
    bool status;
    public float timer;
    public GameObject canvasObject;
    public GameObject playerObject;

    private FillCanvasWithInfo fillCanvas;
    private Transform canvasInfoPosition;
    private Transform playerPosition;
    private PlayerTransform player;
    private InstrumentInfo info;

    // Start is called before the first frame update
    void Start()
    {
        if(canvasObject)
        {
            fillCanvas = canvasObject.GetComponent<FillCanvasWithInfo>();
            canvasInfoPosition = canvasObject.GetComponent<Transform>();
        }
        playerPosition = playerObject.GetComponent<Transform>();
        player = playerObject.GetComponent<PlayerTransform>();
        info = GetComponent<InstrumentInfo>();
    }

    // Update is called once per frame
    void Update()
    {
        if(status)
        {
            timer += Time.deltaTime;
            loadingImage.fillAmount = timer / totalTime;
        }

        if (timer > totalTime)
        {
            timer = 0;
            if(canvasObject)
            {
                fillCanvas.FillInformation(info.fullName, info.year, info.description, info.price);
                // Safe player position and the instrument name
                player.Position = playerPosition.position;
                player.InstrumentName = gameObject.name;
                // Teleport player to the info canvas
                playerPosition.position = new Vector3(canvasInfoPosition.position.x, canvasInfoPosition.position.y, canvasInfoPosition.position.z-1);
                // Creates copy of the instrument next to the info canvas
                GameObject clone = Instantiate(gameObject, new Vector3(playerPosition.position.x+2, playerPosition.position.y, playerPosition.position.z), Quaternion.identity);

                clone.AddComponent<RotateObject>();
                // Disable interactivity script
                clone.GetComponent<ObjectInteraction>().enabled = false;
            }
            else
            {
                Destroy(GameObject.Find(player.InstrumentName + "(Clone)"));
                playerPosition.position = player.Position;
            }
        }
    }

    public void Activated()
    {
        status = true;
    }

    public void Deactivated()
    {
        status = false;
        timer = 0;
        loadingImage.fillAmount = 0;
    }
}
