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

public class NewStartLocalGameScript : MonoBehaviour
{

    public Slider secondsToAnswer;
    public Slider correctsToWin;
    public Slider numberOfPlayer;

    [SerializeField] GameObject playersPanel;
    // Start is called before the first frame update
    void Start()
    {
        gameObject.GetComponent<Button>().onClick.AddListener(StartLocalGame);
    }

    void Update()
    {
        PlayerSetting[] playerSettings = playersPanel.GetComponentsInChildren<PlayerSetting>();
        foreach (PlayerSetting ps in playerSettings) {
            if (ps.nameInput.text.Equals("")) {
                gameObject.GetComponent<Button>().interactable = false;
                ps.nameInput.placeholder.GetComponent<Text>().text = LocalizationManager.Instance.GetText("PLAYER_SETTING_NAME_PLACEHOLDER");
                break;
            }
            gameObject.GetComponent<Button>().interactable = true;
        }
    }
    private void StartLocalGame() {
        Database.Instance.SetLocalOrOnline(Constants.LOCAL);
        List<string> playerNames = new List<string>();

        int correctsToWinInt = (int)correctsToWin.value;
        int numberOfPayersInt = (int)numberOfPlayer.value;
        int secondsToAnswerInt = (int)secondsToAnswer.value;
        int gameId = Database.Instance.SetupNewLocalGame(correctsToWinInt, numberOfPayersInt, secondsToAnswerInt);

        bool okToStart = true;

        Transform newPlayersPanel = GameObject.Find("NewPlayersPanel").transform;
        PlayerSetting[] playerSettings = newPlayersPanel.GetComponentsInChildren<PlayerSetting>();

        for (int i = 0; i < playerSettings.Length; i++) {
            string playerName = playerSettings[i].GetComponent<PlayerSetting>().nameInput.text;
            playerNames.Add(playerName);
        }

        Database.Instance.LinkPlayersToLocalGame(playerNames, gameId);

        PlayerPrefs.SetString(Constants.GAME_MODE, Constants.LOCAL);
        PlayerPrefs.SetInt(Constants.GAME_ID, gameId);
        PlayerPrefs.SetInt(Constants.GAME_QUESTION_TIMER, secondsToAnswerInt);
        PlayerPrefs.SetInt(Constants.GAME_TO_WIN, correctsToWinInt);
        if (okToStart) {
            SceneManager.LoadSceneAsync(Constants.SCENE_NAR_KAMPEN);
        }
    }

}
