﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using PlayFab;
using PlayFab.ClientModels;
using System;

public class PlayerStats : MonoBehaviour {

    public TMP_Text firstPlaceWins;
    public TMP_Text secondPlaceWins;
    public TMP_Text thirdPlaceWins;
    public TMP_Text totalRaces;

    int first;
    int second;
    int third;
    int total;

    static string tempTrackName = "";
    public Vector2 playerTimes = Vector2.zero;
    public bool recievedTimes = false;

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

    public void ComparePlayerTimes (string trackName, float lapTime, float raceTime)
    {
        StartCoroutine(WaitForTimeResults(trackName, lapTime, raceTime));
    }

    IEnumerator WaitForTimeResults (string trackName, float lapTime, float raceTime)
    {
        CheckBestPlayerTimes(trackName);

        while (!recievedTimes)
        {
            yield return new WaitForSeconds(0.1f);
        }

        recievedTimes = false;

        Vector2 oldTimes = playerTimes;
        playerTimes = Vector2.zero;

        if (lapTime >= oldTimes.x && lapTime != 0f && oldTimes.x != 0f)
        {
            Debug.Log(trackName + " Lap Time Unchanged");
            lapTime = (int)oldTimes.x;
        }
        else
        {
            Debug.Log(trackName + " Lap Time Updated");
        }

        if (raceTime >= oldTimes.y && raceTime != 0f && oldTimes.y != 0f)
        {
            Debug.Log(trackName + " Race Time Unchanged");
            raceTime = (int)oldTimes.y;
        }
        else
        {
            Debug.Log(trackName + " Race Time Updated");
        }

        Debug.Log("New Times: " + lapTime.ToString() + ", " + raceTime.ToString());

        PlayfabCloudScriptAPI.UpdateBestTimes(trackName, lapTime, raceTime);
        yield return null;
    }

    void CheckBestPlayerTimes(string trackName)
    {
        recievedTimes = false;
        playerTimes = Vector2.zero;
        tempTrackName = "";
        tempTrackName = trackName;
        if(tempTrackName == "")
        {
            Debug.Log("Track name is Empty");
            recievedTimes = true;
            return;
        }
        var request = new GetUserDataRequest { };
        PlayFabClientAPI.GetUserData(request, GetPlayerTimes, result => Debug.Log("Error on request: " + result.ErrorMessage));
    }

    void GetPlayerTimes(GetUserDataResult result)
    {
        if (tempTrackName == "")
        {
            Debug.Log("Track name is Empty");
            recievedTimes = true;
            return;
        }

        float lapTime = 0f;
        float raceTime = 0f;

        string lapTimeKey = tempTrackName + "_bestLapTime";
        string raceTimeKey = tempTrackName + "_bestRaceTime";

        string bestLapTime = "";
        string bestRaceTime = "";


        if (result.Data.ContainsKey(lapTimeKey))
        {
            bestLapTime = result.Data[lapTimeKey].Value;
            float.TryParse(bestLapTime, out lapTime);
        }

        if (result.Data.ContainsKey(raceTimeKey))
        {
            bestRaceTime = result.Data[raceTimeKey].Value;
            float.TryParse(bestRaceTime, out raceTime);
        }

        playerTimes = new Vector2(lapTime, raceTime);

        Debug.Log("Current Times { " + lapTimeKey + ": " + bestLapTime + ", " + raceTimeKey + ": " + bestRaceTime + " }");

        recievedTimes = true;
    }

    private void UpdatePlayerStatSheet(GetPlayerStatisticsResult obj) {
        List<StatisticValue> stats = obj.Statistics;

        foreach (StatisticValue stat in stats)
        {
            switch (stat.StatisticName)
            {
                case "1st Place Wins":
                    first = stat.Value;
                    break;
                case "2nd Place Wins":
                    second = stat.Value;
                    break;
                case "3rd Place Wins":
                    third = stat.Value;
                    break;
                case "Total Races":
                    total = stat.Value;
                    break;
                default:
                    break;
            }
        }

        firstPlaceWins.SetText(first.ToString());
        secondPlaceWins.SetText(second.ToString());
        thirdPlaceWins.SetText(third.ToString());
        totalRaces.SetText(total.ToString());
    }
}
