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

public class Webcam : MonoBehaviour
{
    int camdex = 0;
    WebCamTexture tex;

    public RawImage display;
    public Button feedback;
    public GameObject popup;
    public TextMeshProUGUI dynamic;

    void Awake(){
        popup.SetActive(false);

        WebCamDevice device = WebCamTexture.devices[camdex];
        tex = new WebCamTexture(device.name);
        display.texture = tex;

        tex.Play();
    }

    public void SwapCam()
    {
        if (WebCamTexture.devices.Length > 0)
        {
            // Stop the old camera
            display.texture = null;
            tex.Stop();
            tex = null;

            // Find the new camera
            camdex += 1;
            camdex %= WebCamTexture.devices.Length;

            // Start the new camera
            WebCamDevice device = WebCamTexture.devices[camdex];
            tex = new WebCamTexture(device.name);
            display.texture = tex;

            tex.Play();
        }
    }

    // Scene changing is implemented here to avoid problems with webcam
    public void LoadScene(string sceneName)
    {
        display.texture = null;
        tex.Stop();
        tex = null;

        SceneManager.LoadScene(sceneName);
    }

    public void Show_feedback(){
        if(popup.activeSelf){
            dynamic.text = "";
            popup.SetActive(false);
            return;
        }
        double index = UnityEngine.Random.value;
        if(index < 0.5){
            dynamic.text = "Poor";
        }
        else if(index > 0.8){
            dynamic.text = "Excellent";
        }
        else{
            dynamic.text = "Good";
        }
        popup.SetActive(true);
    }
}
