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

public class Manager : MonoBehaviour
{
    private static Manager instance;
    public static Manager Instance
    {
        get
        {
            if(instance == null)
                instance = FindObjectOfType<Manager>();
            return instance;
        }
    }

    public Image Screen1;
    public Image Screen2;
    public GameObject Plane;
    public Transform Player1;
    public Transform Player2;
    public Transform CameraTF;
    public AudioSource sound;

    public bool is2D;
    public bool begin = false;

    private void Start()
    {
        is2D = true;
        Screen1.enabled = false;
        Screen2.enabled = false;
    }

    public void SwitchView()
    {
        is2D = false;
        Plane.SetActive(false);
        Screen1.enabled = true;
        Screen2.enabled = true;
    }

    public void Result(int win)
    {
        begin = false;
        Screen1.enabled = false;
        Screen2.enabled = false;
        Vector3 startPos = CameraTF.position;
        Vector3 endPos = win == 0 ?
            Player1.position + Player1.forward*1.5f + Vector3.up :
            Player2.position + Player2.forward*1.5f + Vector3.up ;
        Vector3 startRot = CameraTF.eulerAngles;
        Vector3 endRot = win==0 ? Player1.eulerAngles + Vector3.up*180 : 
                                  Player2.eulerAngles + Vector3.up*180 ;
        
        Debug.Log("Result: " + win);
        StartCoroutine(DelayMoving(startPos, win, startRot, endRot));  
    }
    IEnumerator DelayMoving(Vector3 sp, int win, Vector3 sr, Vector3 er)
    {
        for(float t = 0; t <= 1; t += 0.004f)
        {
            Vector3 ep = win == 0 ?
            Player1.position + Player1.forward * 1.5f + Vector3.up :
            Player2.position + Player2.forward * 1.5f + Vector3.up;
            Vector3 pos;
            pos.x = Mathf.Lerp(sp.x, ep.x, t);
            pos.y = Mathf.Lerp(sp.y, ep.y, t);
            pos.z = Mathf.Lerp(sp.z, ep.z, t);
            Vector3 rot;
            rot.x = Mathf.Lerp(sr.x, er.x, t);
            rot.y = Mathf.Lerp(sr.y, er.y, t);
            rot.z = Mathf.Lerp(sr.z, er.z, t);
            CameraTF.position = pos;
            CameraTF.localEulerAngles = rot;
            yield return new WaitForEndOfFrame();
        }
    }

    public void PlayMusic(string name)
    {
        AudioClip clip = Resources.Load<AudioClip>("Sound/" + name);
        sound.clip = clip;
        sound.Play();
    }

    public void PlaySound(string name)
    {
        AudioClip clip = Resources.Load<AudioClip>("Sound/" + name);
        sound.PlayOneShot(clip);
    }
}
