using UnityEngine;
using UnityEngine.UI;
using TwitchInGames;
using System.Collections;
using System;

public class UserExample : MonoBehaviour {

    [SerializeField]
    private GameObject panel;

    [SerializeField]
    private Image profileImage;

    [SerializeField]
    private Text displayName;

    [SerializeField]
    private Text id;

    [SerializeField]
    private Text email;

    [SerializeField]
    private Text viewCount;

    [SerializeField]
    private Text bio;

    [SerializeField]
    private Button downloadButton;

    private User currentUser;

    public GameObject Panel { get { return panel; } }

    public void FetchCurrentUser(string clientId, string token) {        
            StartCoroutine(InternalFetchCurrentUser(clientId, token));
    }

    public void DownloadProfileImage() {
        StartCoroutine(InternalDownloadProfileImage());
    }

    private IEnumerator InternalFetchCurrentUser(string clientId, string token) {

        /* 
         * To fetch other users without token (no email address in response), use the followings:
         * coroutine = User.FetchOtherById(clientId, id);
         * coroutine = User.FetchOtherByLogin(clientId, login);
        */

        var coroutine = User.FetchCurrent(clientId,token);

        yield return coroutine;
        try {
            currentUser = coroutine.Value;
            OnFetchUser();
        }
        catch (Exception ex) {
            Debug.LogErrorFormat(ex.ToString());
        }
    }

    private void OnFetchUser() {        
        displayName.text = currentUser.DisplayName;
        id.text = currentUser.Id;
        email.text = currentUser.Email;
        viewCount.text = currentUser.ViewCount.ToString();
        bio.text = currentUser.Description;
        StartCoroutine(DisplayProfileImage());

        downloadButton.gameObject.SetActive(true);
    }

    private IEnumerator DisplayProfileImage() {
        var url = currentUser.ProfileImageUrl == "" ? "https://static-cdn.jtvnw.net/jtv_user_pictures/xarth/404_user_300x300.png" : currentUser.ProfileImageUrl;
        WWW www = new WWW(url);
        yield return www;
        profileImage.sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), new Vector2(0, 0));
    }

    private IEnumerator InternalDownloadProfileImage() {
        // Get the user.
        var userCoroutine = User.FetchOtherById(TwitchSettings.ClientId, id.text);
        yield return userCoroutine;
        User user;
        try {
            user = userCoroutine.Value;
        }
        catch (Exception ex) {
            Debug.LogErrorFormat("[TwitchInGames] DownloadProfileImage error: {0}", ex);
            yield break;
        }

        // Get the user's profile image.
        var imageCoroutine = user.FetchProfileImage();
        yield return imageCoroutine;
        try {
            var image = imageCoroutine.Value;
            OnDownloadProfileImage(image);
        }
        catch (Exception ex) {
            Debug.LogErrorFormat("[TwitchInGames] DownloadProfileImage error: {0}", ex);
        }
    }

    private void OnDownloadProfileImage(Texture2D imageTexture) {
        if (imageTexture != null) {
            var textureData = imageTexture.GetRawTextureData();
            Debug.LogFormat("[TwitchInGames] Profile image downloaded; size is {0} bytes.", textureData.Length);
        }
        else {
            Debug.LogFormat("[TwitchInGames] No Image downloaded.");
        }
    }
}
