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

public class NewOnlineGame : MonoBehaviour
{

    public Button inviteButton;
    public Button startButton;

    public InputField correctAnswersToWin;
    public InputField timeLimitPerQuestion;
    public InputField timeLimitPerPlayer;

    Text invitedCountText;
    InvitePanelScript ips;

    // Start is called before the first frame update
    void Start()
    {
        inviteButton.onClick.AddListener(OpenInvitePanel);
        startButton.onClick.AddListener(StartNewGame);
        invitedCountText = GameObject.Find("InvitedCountText").GetComponent<Text>();
    }

    private void Update() {
        if (ips == null) {
            ips = GameObject.Find("InvitePanel").GetComponent<InvitePanelScript>();
        }

        if (ips.AreThereInvites()) {
            invitedCountText.GetComponent<CanvasGroup>().alpha = 1f;
            string text = LocalizationManager.Instance.GetText("INVITE_COUNT_TEXT");
            int invitedCount = ips.InvitedCount();
            text = String.Format(text, invitedCount.ToString());
            invitedCountText.text = text;
            startButton.interactable = true;
        }
    }

    private void StartNewGame() {
        // Collect all information for new game;
        // Send to Database;
        int timeLimitQuestion = GetInputFieldValue(timeLimitPerQuestion);
        int timeLimitPlayer = GetInputFieldValue(timeLimitPerPlayer);
        int correctToWin = GetInputFieldValue(correctAnswersToWin);
        List<InviteSearchResult> inviteUsers = ips.GetSelectedUsersForInvite();
        OnlineDatabase.Instance.SetupNewOnlineGame(timeLimitQuestion, timeLimitPlayer, correctToWin, inviteUsers);

        // Reload Online Games panel, new prefab Online game pending.
        Hide();
    }

    private int GetInputFieldValue(InputField inputField) {
        int returnValue = 0;
        if (inputField.text.Equals("")) {
            string text = Regex.Match(inputField.placeholder.GetComponent<Text>().text, @"\d+").Value;
            Int32.TryParse(text, out returnValue);
        } else {
            string text = Regex.Match(inputField.text, @"\d+").Value;
            Int32.TryParse(text, out returnValue);
        }

        return returnValue;
    }

    private void OpenInvitePanel() {
        GameObject.Find("InvitePanel").GetComponent<InvitePanelScript>().ShowPanel();
    }

    private void Hide() {
        GameObject.Find("Main Panel").GetComponent<MainMenu>().HideNewGamesPanel();
    }
}
