﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class LocalHighScore : HighScore {

    private string[] Random_Names = new string[] { "John", "Peter", "Jane", "Bob", "Joe" };

    private string UserDataKey
    {
        get { return HashKey + "_HighScore"; }
    }

    public override void LoadUserData()
    {
        base.LoadUserData();
        //PlayerPrefs.DeleteKey(UserDataKey);
        string userData = PlayerPrefs.GetString(UserDataKey);

        if (!string.IsNullOrEmpty(userData))
        {
            Debug.Log(userData);
            // Deserialise the user data

            // Create a binary formatter in readiness to deserialise the binary data
            BinaryFormatter bf = new BinaryFormatter();

            // Create a memory stream with the data
            MemoryStream ms = new MemoryStream(Convert.FromBase64String(userData));

            // Deserialise the binary data read into memory from binary format back to a List of Users Data
            Users = bf.Deserialize(ms) as List<UserData>;

            UpdateRandomScores();
        } else
        {
            LoadRandomUsers();
        }

        // Sort the results by score in reverse order
        SortByScore(); // Method defined in HighSore
        Users.Reverse();
    }

    private void LoadRandomUsers()
    {
        foreach (string name in Random_Names)
        {
            UserData user = new UserData();
            user.Name = name;
            user.Score = Mathf.FloorToInt(UnityEngine.Random.value * 100);
            Users.Add(user);
        }
    }

    private void UpdateRandomScores()
    {
        if (Users == null)
            return;

        foreach (string name in Random_Names)
        {
            UserData existingUser = FindUser(name);
            if (existingUser != null)
            {
                int newScore = Mathf.FloorToInt(UnityEngine.Random.value * 100);
                if (newScore > existingUser.Score)
                {
                    existingUser.Score = newScore;
                }
            }
        }
    }

    public override void SaveUserData(UserData user)
    {
        // If no user to save, return and exit early
        if (user == null)
        {
            return;
        }
        
        // If users is null, load the users first
        if (Users == null)
        {
            LoadUserData();
        }

        // Check if this is a score for an existing user in the list, find the user by name
        UserData existingUser = FindUser(user.Name);
        if (existingUser != null)
        {
            // If it is an existing user, only update score if new score is higher
            if (user.Score > existingUser.Score)
                existingUser.Score = user.Score;
        } else
        {
            // If user does not exist, add
            Users.Add(user);
        }

        // Serialise the data to by binary format

        // Create a binary formatter in readiness to serialise the list of users to binary format
        BinaryFormatter bf = new BinaryFormatter();

        // Create a memory stream with the data
        MemoryStream ms = new MemoryStream();

        // Serialise the Users data to binary format
        bf.Serialize(ms, Users);

        // Add the data from memory to player prefs using the data key
        PlayerPrefs.SetString(UserDataKey, Convert.ToBase64String(ms.GetBuffer()));
        PlayerPrefs.Save();
    }

}
