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

namespace TwitchInGames.Test {
    public class UnitTest_Follow : UnitTest_Auth {
#pragma warning disable 649 // Field '*' is never assigned to, and will always have its default value *
        [SerializeField]
        private GameObject followerInfoPrefab;

        [SerializeField]
        private GameObject messagePrefab;

        [SerializeField]
        private GameObject outputPanel;

        [SerializeField]
        private Slider firstSlider;

        [SerializeField]
        private Dropdown cursorDropdown;

        [SerializeField]
        private InputField cursor;

        [SerializeField]
        private InputField userId;
#pragma warning restore 649

        public void GetFollowers() {
            StartCoroutine(InternalGetFollowers());
        }

        private IEnumerator InternalGetFollowers() {
            var direction = FollowersRequest.PaginationDirection.None;
            if(cursorDropdown.value == 0) {
                direction = FollowersRequest.PaginationDirection.Forward;
            } else {
                direction = FollowersRequest.PaginationDirection.Backward;
            }
            var followersRequest = new FollowersRequest {
                Count = (uint)firstSlider.value,
                Cursor = cursor.text,
                Direction = direction
            };
            var coroutine = followersRequest.Fetch(clientId, authToken, userId.text);
            yield return coroutine;
            try {
                var followersResponse = coroutine.Value;
                OnGetFollowers(followersResponse);
            } catch(Exception ex) {
                Debug.LogErrorFormat("GetFollower error: {0}", ex);
            }
        }

        private void OnGetFollowers(FollowersResponse followersResponse) {
            foreach(Transform child in outputPanel.transform) {
                Destroy(child.gameObject);
            }
            cursor.text = followersResponse.Cursor;
            Debug.Log("Pagination: " + followersResponse.Cursor);

            GameObject log1 = Instantiate(messagePrefab, outputPanel.transform);
            log1.GetComponent<Message>().Init(new string[] { "Log", "Got " + followersResponse.Followers.Count.ToString() + " followers." });

            foreach(var follower in followersResponse.Followers) {
                GameObject gameobject = Instantiate(followerInfoPrefab, outputPanel.transform);
                Dictionary<string, string> fields = new Dictionary<string, string>(2) {
                    { "user_id", follower.UserId },
                    { "followed_at", follower.FollowedAt.ToString() }
                };
                gameobject.GetComponent<InfoHolder>().Init(fields);
            }
        }
    }
}
