using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Networking;

public class YoutubeChatReader : MonoBehaviour
{
    [SerializeField] float _checkChatDelay = 10f;
    Coroutine _routine;
    string _nextPageToken;

    void OnEnable() => _routine = StartCoroutine(ProcessLoop());
    void OnDisable() => StopCoroutine(_routine);

    IEnumerator FindChats()
    {
        string finalRequestUrl = HiddenData.getBroadcastsUrl;
        if (!string.IsNullOrWhiteSpace(_nextPageToken))
            finalRequestUrl += "&pageToken=" + _nextPageToken;
            
        UnityWebRequest www = UnityWebRequest.Get(finalRequestUrl);
        yield return www.SendWebRequest();
        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log("Handling Response");
            Debug.Log(www.downloadHandler.text);
            BroadcastData.Root myDeserializedClass = JsonUtility.FromJson<BroadcastData.Root>(www.downloadHandler.text);
            Debug.Log(myDeserializedClass.items.Count);
            foreach (var item in myDeserializedClass.items)
            {
                if (!string.IsNullOrWhiteSpace(item.snippet.liveChatId))
                {
                    AddLiveChatToList(item.snippet);
                }
            }
            //_nextPageToken = myDeserializedClass.nextPageToken;

            //ProcessPicks(myDeserializedClass);
        }
    }

    void AddLiveChatToList(BroadcastData.Snippet itemSnippet)
    {
        Debug.Log($"{{itemSnippet.title}}  {{itemSnippet.liveChatId}}");
    }

    bool _hasChat;
    IEnumerator ProcessLoop()
    {
        while (true)
        {
            //yield return FindChats();
            //if (_hasChat)
            {
                yield return CheckChat();
            }

            yield return new WaitForSeconds(Mathf.Max(1f, _checkChatDelay));
        }
    }

    IEnumerator CheckChat()
    {
        Debug.Log("Sending request");
        string finalRequestUrl = HiddenData.getChatMessagesUrl;
        if (!string.IsNullOrWhiteSpace(_nextPageToken))
            finalRequestUrl += "&pageToken=" + _nextPageToken;
            
        UnityWebRequest www = UnityWebRequest.Get(finalRequestUrl);
        yield return www.SendWebRequest();
        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log("Handling Response");
            Debug.Log(www.downloadHandler.text);
            LiveChatResponse myDeserializedClass = JsonUtility.FromJson<LiveChatResponse>(www.downloadHandler.text);
            Debug.Log(myDeserializedClass.items.Count);
            _nextPageToken = myDeserializedClass.nextPageToken;

            ProcessPicks(myDeserializedClass);
        }
    }

    void ProcessPicks(LiveChatResponse liveChatResponse)
    {
        foreach (var item in liveChatResponse.items)
        {
            if (string.IsNullOrWhiteSpace(item.authorDetails?.displayName))
                continue;

            ProcessMessageFromPlayer(item.authorDetails.displayName, item.snippet.displayMessage);
        }
    }

    void ProcessMessageFromPlayer(string playerName, string message)
    {
	    _playerBuilder.ProcessBuildFromText(playerName, message);
    }


    void OnValidate()
    {
        _playerBuilder = FindObjectOfType<PlayerBuilder>();
    }

    [SerializeField] PlayerBuilder _playerBuilder;
}

public enum Models
{
    Knight,
    Lizard,
    Rat,
    Werewolf,
    Worm,
    Chest,
    Crab,
    Specter,
    Demon,
    Beholder
}



public class BroadcastData
{
    // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
    public class PageInfo
    {
        public int totalResults { get; set; }
        public int resultsPerPage { get; set; }
    }

    public class Default
    {
        public string url { get; set; }
        public int width { get; set; }
        public int height { get; set; }
    }

    public class Medium
    {
        public string url { get; set; }
        public int width { get; set; }
        public int height { get; set; }
    }

    public class High
    {
        public string url { get; set; }
        public int width { get; set; }
        public int height { get; set; }
    }

    public class Standard
    {
        public string url { get; set; }
        public int width { get; set; }
        public int height { get; set; }
    }

    public class Maxres
    {
        public string url { get; set; }
        public int width { get; set; }
        public int height { get; set; }
    }

    public class Thumbnails
    {
        public Default @default { get; set; }
        public Medium medium { get; set; }
        public High high { get; set; }
        public Standard standard { get; set; }
        public Maxres maxres { get; set; }
    }

    public class Snippet
    {
        public DateTime publishedAt { get; set; }
        public string channelId { get; set; }
        public string title { get; set; }
        public string description { get; set; }
        public Thumbnails thumbnails { get; set; }
        public bool isDefaultBroadcast { get; set; }
        public string liveChatId { get; set; }
        public DateTime? scheduledStartTime { get; set; }
    }

    public class Status
    {
        public string lifeCycleStatus { get; set; }
        public string privacyStatus { get; set; }
        public string recordingStatus { get; set; }
        public bool madeForKids { get; set; }
        public bool selfDeclaredMadeForKids { get; set; }
    }

    public class MonitorStream
    {
        public bool enableMonitorStream { get; set; }
        public int broadcastStreamDelayMs { get; set; }
        public string embedHtml { get; set; }
    }

    public class ContentDetails
    {
        public string boundStreamId { get; set; }
        public DateTime boundStreamLastUpdateTimeMs { get; set; }
        public MonitorStream monitorStream { get; set; }
        public bool enableEmbed { get; set; }
        public bool enableDvr { get; set; }
        public bool enableContentEncryption { get; set; }
        public bool startWithSlate { get; set; }
        public bool recordFromStart { get; set; }
        public bool enableClosedCaptions { get; set; }
        public string closedCaptionsType { get; set; }
        public bool enableLowLatency { get; set; }
        public string latencyPreference { get; set; }
        public string projection { get; set; }
        public bool enableAutoStart { get; set; }
        public bool enableAutoStop { get; set; }
    }

    public class Statistics
    {
    }

    public class Item
    {
        public string kind { get; set; }
        public string etag { get; set; }
        public string id { get; set; }
        public Snippet snippet { get; set; }
        public Status status { get; set; }
        public ContentDetails contentDetails { get; set; }
        public Statistics statistics { get; set; }
    }

    public class Root
    {
        public string kind { get; set; }
        public string etag { get; set; }
        public PageInfo pageInfo { get; set; }
        public List<Item> items { get; set; }
    }


}