using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using TMPro;
using PlayFab;
using PlayFab.ClientModels;
using PlayFab.Json;


public class PersistantPlayerStats : MonoBehaviour {

	public static PersistantPlayerStats myStats;

	public static int currentXP;
	public static int currentRank;
	public static int currentScore;
	public static int dailyLogins = 0;
	bool loginSet = false;
	public static DateTime oldDate;
	public Vector4 defaultColor;

	public GameObject dailyStreakDisplay;
	public TextMeshProUGUI dailyStreak;

	// Use this for initialization
	void Awake () {
		if (myStats == null) {
			myStats = this;
			DontDestroyOnLoad (gameObject);
		} else if (myStats != this) {
			Destroy (gameObject);
		}
	}

	void OnEnable() {
		SceneManager.sceneLoaded += SceneLoadCheck;
	}

	void OnDestroy () {
		SceneManager.sceneLoaded -= SceneLoadCheck;
	}

	// sets variables based on what scene has been loaded
	void SceneLoadCheck(Scene scene, LoadSceneMode mode) {

		// check if the scene that was just loaded is the login
		if (scene.name == "Login") {
			Nullify.ResetPlayerStats ();
		}

		// check if the scene that was just loaded is the main menu
		if (scene.name == "Main Menu") {
			var requestDate = new GetUserDataRequest { };
			PlayFabClientAPI.GetUserData(requestDate, GetLastLogin, result => Debug.Log("Error on request: " + result.ErrorMessage));

			GetStats ();
		}
	}
	
	// Update is called once per frame
	void Update () {

		if (SceneManager.GetActiveScene ().name == "Main Menu") {
			if (!dailyStreakDisplay) {
				dailyStreakDisplay = GameObject.Find ("Consecutive Days");
			}
			if (dailyStreakDisplay) {
				dailyStreak = dailyStreakDisplay.GetComponent<TextMeshProUGUI> ();
				dailyStreak.SetText (dailyLogins.ToString());
			}
		}
	}

	public static Vector4 StringToVector4(string sVector){
		if (sVector.StartsWith ("RGBA(") && sVector.EndsWith (")")) {
			sVector = sVector.Substring (5, sVector.Length - 6);
		}

		string[] sArray = sVector.Split (',');

		Vector4 result = new Vector4 (
			float.Parse (sArray [0]),
	        float.Parse (sArray [1]),
		    float.Parse (sArray [2]),
            float.Parse (sArray [3]));
		
		return result;
	}

	void GetLastLogin (GetUserDataResult result) {
		
		if (result.Data.ContainsKey("lastLoginDate")) {
			string loginDateString = result.Data["lastLoginDate"].Value;
			oldDate = Convert.ToDateTime (loginDateString);
		}
		StartCoroutine (GetUTCTime ());
	}

	public IEnumerator GetUTCTime () {

		while (!loginSet) {
			yield return new WaitForSecondsRealtime (0.1f);
		}

		PlayFabClientAPI.GetTime (
			new GetTimeRequest (),
			SetDailyLoginTime,
			error => Debug.LogError (error.GenerateErrorReport ())
		);
		yield return null;
	}

	public void SetDailyLoginTime (GetTimeResult result) {

		Dictionary<string, float> streakSender = new Dictionary<string, float> ();

		if (dailyLogins == 0 || dailyLogins == null) {
			dailyLogins = 1;
			oldDate = result.Time.ToLocalTime();
			streakSender.Add ("Streak", (float)dailyLogins);
			Debug.Log ("Began first streak!");
		} else {
			TimeSpan streakCheck = result.Time.ToLocalTime().Subtract (oldDate);

			if (streakCheck.Days == 1) {
				oldDate = result.Time.ToLocalTime();
				dailyLogins++;
				streakSender.Add ("Streak", (float)dailyLogins);
				Debug.Log ("Streak Increased!");

			} else if (streakCheck.Days == 0) {
				//Debug.Log ("What is today, but yesterday's tomorrow?");
			} else {
				dailyLogins = 1;
				oldDate = result.Time.ToLocalTime();
				streakSender.Add ("Streak", (float)dailyLogins);
				Debug.Log ("Streak Reset!");
			}
		}
        
        var req = new GetUserDataRequest { Keys = new List<string> { "highestStreak" } };
        PlayFabClientAPI.GetUserData(req, OnSuccesfulGetHighestStreak, OnFailedGetHighestStreak);
        
    }

    void OnFailedGetHighestStreak(PlayFabError error) {
        Dictionary<string, string> update = new Dictionary<string, string>() {
            { "lastLoginDate", oldDate.ToString() }
        };

        var request = new UpdateUserDataRequest { Data = update };
        PlayFabClientAPI.UpdateUserData(request, null, updateErrors => Debug.LogError("Error on request: " + updateErrors.ErrorMessage));
    }

    void OnSuccesfulGetHighestStreak(GetUserDataResult results) {
        int currentHighestStreak = 0;
        if (results.Data.ContainsKey("highestStreak")) {
            currentHighestStreak = System.Convert.ToInt32(results.Data["highestStreak"].Value);
        }

        Dictionary<string, string> update = new Dictionary<string, string>() {
            { "lastLoginDate", oldDate.ToString() },
            { "highestStreak", (dailyLogins > currentHighestStreak ? dailyLogins : currentHighestStreak).ToString() }
        };

        var request = new UpdateUserDataRequest { Data = update };
        PlayFabClientAPI.UpdateUserData(request, null, updateErrors => Debug.LogError("Error on request: " + updateErrors.ErrorMessage));
    }



	public void GetStats () {
		PlayFabClientAPI.GetPlayerStatistics (
			new GetPlayerStatisticsRequest (),
			UpdatePlayerStats,
			error => Debug.LogError (error.GenerateErrorReport ())
		);
	}

	public void UpdatePlayerStats (GetPlayerStatisticsResult result) {
		//Debug.Log ("Recieved the following Statistics:");
		foreach (var eachStat in result.Statistics) {

		}

		loginSet = true;

		if (currentRank < 1 || currentRank == null) {

            Debug.Log ("Set to Rank 1");
			currentRank = 1;
		}

		if (currentScore == null) {
			currentScore = 0;
		}

	}

}
