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

public class RecordsDisplay : MonoBehaviour
{
    public GameObject recordPrefab;
    public List<Record> playerRecords;


    void Start()
    {
        playerRecords.Clear();
        GetPlayerTimes();
    }

    void GetPlayerTimes()
    {
        var request = new GetUserDataRequest { };
        PlayFabClientAPI.GetUserData(request, ReadPlayerTimes, result => Debug.Log("Error on request: " + result.ErrorMessage));
    }

    void ReadPlayerTimes(GetUserDataResult result)
    {

        Debug.Log("Got Records");

        foreach (KeyValuePair<string, UserDataRecord> pdk in result.Data)
        {
            if(pdk.Key == "moodleUsername")
            {
                continue;
            }

            foreach (KeyValuePair<string, UserDataRecord> pdk2 in result.Data)
            {
                if (pdk2.Key == "moodleUsername" || pdk.Key == pdk2.Key)
                {
                    continue;
                }

                string[] newString1;
                string[] newString2;

                newString1 = pdk.Key.Split('_');
                newString2 = pdk2.Key.Split('_');

                if(newString1[0] == newString2[0])
                {
                    string lapTxt = "";
                    string raceTxt = "";

                    float lapVal = 0f;
                    float raceVal = 0f;

                    if (newString1[1].Contains("Lap"))
                    {
                        float.TryParse(result.Data[pdk.Key].Value, out lapVal);
                        float.TryParse(result.Data[pdk2.Key].Value, out raceVal);

                        lapTxt = FormatTime(lapVal);
                        raceTxt = FormatTime(raceVal);
                    } else if (newString1[1].Contains("Race"))
                    {
                        float.TryParse(result.Data[pdk.Key].Value, out raceVal);
                        float.TryParse(result.Data[pdk2.Key].Value, out lapVal);

                        raceTxt = FormatTime(raceVal);
                        lapTxt = FormatTime(lapVal);
                    }

                    Record newRecord = new Record(newString1[0], lapTxt, raceTxt);

                    if (playerRecords.Count > 0)
                    {
                        bool recordExists = false;
                        for (int i = 0; i < playerRecords.Count; i++)
                        {
                            if(newRecord.track == playerRecords[i].track)
                            {
                                Debug.Log("hit");
                                recordExists = true;
                                break;
                            }
                        }
                        if (!recordExists)
                        {
                            playerRecords.Add(newRecord);
                        }
                    }
                    else
                    {
                        playerRecords.Add(newRecord);
                    }
                }
            }
        }

        DisplayRecords();
    }

    string FormatTime(float time)
    {
        int intTime = (int)time;
        int minutes = (int)time / 60;
        int seconds = (int)time % 60;
        int milliseconds = (int)(time * 1000) % 1000;
        string timeText = string.Format("{0:00}:{1:00}:{2:000}", minutes, seconds, milliseconds);
        return timeText;
    }

    void DisplayRecords()
    {
        GameObject newRecord;
        if (playerRecords.Count > 0)
        {
            for (int i = 0; i < playerRecords.Count; i++)
            {
                newRecord = GameObject.Instantiate(recordPrefab, transform);
                newRecord.GetComponent<RecordHolder>().AssignTexts(playerRecords[i].track, playerRecords[i].lap, playerRecords[i].race);
            }
        }

        Debug.Log("Ran Records");
    }
}
/// <summary>
/// Base class for record keeping.
/// </summary>
[System.Serializable]
public class Record
{
    public string track, lap, race;

    public Record(string trackName, string lapTime, string raceTime)
    {
        track = trackName;
        lap = lapTime;
        race = raceTime;
    }
}
