using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.InputSystem;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class MenuAim : MonoBehaviour{

    public GameObject gun;

    [SerializeField] Button defaultSelected = default;
    [SerializeField] Button creditsBack = default;
    [SerializeField] Button creditsButton = default;
    bool inCredits;
    float aimVelocity;

    [SerializeField] PlayerInput playerInput = default;
    string currentControlScheme;
    Vector2 aim;

    void Start(){
        AudioManager.instance.Play("MenuTheme");
    }

    public void MousePos(InputAction.CallbackContext state){
        aim = state.ReadValue<Vector2>();
    }

    // Update is called once per frame
    void Update(){
        if(currentControlScheme == "Keyboard"){
            Vector2 mousePos = Camera.main.ScreenToWorldPoint(aim) - transform.position;
            float rotZ = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
            gun.transform.rotation = Quaternion.Euler(0f, 0f, Mathf.SmoothDampAngle(gun.transform.eulerAngles.z, rotZ + 180, ref aimVelocity, .1f));
        }else{
            Vector2 mousePos = EventSystem.current.currentSelectedGameObject.transform.position - transform.position;
            float rotZ = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
            gun.transform.rotation = Quaternion.Euler(0f, 0f, Mathf.SmoothDampAngle(gun.transform.eulerAngles.z, rotZ + 180, ref aimVelocity, .1f));
        }

        if (playerInput.currentControlScheme != currentControlScheme){
            currentControlScheme = playerInput.currentControlScheme;
            if(currentControlScheme == "Keyboard"){
                Cursor.lockState = CursorLockMode.None;
                EventSystem.current.SetSelectedGameObject(null);
            }else{
                if (inCredits)
                    creditsBack.Select();
                else
                    defaultSelected.Select();
                Cursor.lockState = CursorLockMode.Locked;
            }
        }
    }

    public void SelectCredits(){
        if(currentControlScheme == "Keyboard")
            EventSystem.current.SetSelectedGameObject(null);
        else
            creditsBack.Select();
        inCredits = true;
    }
    public void QuitCredits(){
        if (currentControlScheme == "Keyboard")
            EventSystem.current.SetSelectedGameObject(null);
        else
            creditsButton.Select();
        inCredits = false;
    }

    public void Play(){
        SceneManager.LoadScene(1);
    }

    public void Quit(){
        Application.Quit();
    }

    public void OpenURL(){
        Application.OpenURL("https://geri8.itch.io/");
    }

    public void PlaySound(string sound){
        AudioManager.instance.Play(sound);
    }
}
