using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Collections.Generic;
using System.Text;

public class TopScore
{
    public string Name;
    public int Score;
}

public delegate void HighScoreEvent(WebServerHighScores sender);

// Web Server High Score Module
// Usage:
// - Attach as a component to an object
// - Set the public "GameName" property to the name of your game
// - To submit a high score call SubmitHighScore
// - To force a refresh of the high score list call GetTopScores
// - You can subscribe to HighScoresUpdated event to be notified whenever GetTopScores has finished refreshing
public class WebServerHighScores : MonoBehaviour {

    public string GameName = "Spinach";

    public List<TopScore> TopScores = new List<TopScore>();
    public List<TopScore> TopScoresDaily = new List<TopScore>();

    public event HighScoreEvent HighScoresUpdated;

    private string privateKey = "WYATT_CHENG_GAMEJAM_PRIVATE_KEY";
    private string AddScoreURL = "http://www.wyattcheng.com/games/LeaderboardWebserver/AddScore.php?";
    private string TopScoresURL = "http://www.wyattcheng.com/games/LeaderboardWebserver/TopScores.php";
    private string TopScoresDailyURL = "http://www.wyattcheng.com/games/LeaderboardWebserver/TopScoresDaily.php";
    private string RankURL = "http://www.wyattcheng.com/games/LeaderboardWebserver/GrabRank.php?";

    public string Md5Sum(string strToEncrypt)
    {
        System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
        byte[] bytes = ue.GetBytes(strToEncrypt);

        // encrypt bytes
        System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] hashBytes = md5.ComputeHash(bytes);

        // Convert the encrypted bytes back to a string (base 16)
        string hashString = "";

        for (int i = 0; i < hashBytes.Length; i++)
        {
            hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
        }

        return hashString.PadLeft(32, '0');
    }

    IEnumerator AddScore(string name, int score)
    {
        string hash = Md5Sum(name + score + privateKey);

        string query = AddScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash + "&game=" + GameName;

        WWW ScorePost = new WWW(query);
        yield return ScorePost;

        if (ScorePost.error == null)
        {
            // StartCoroutine(GetTopScores());
            // StartCoroutine(GetTopScoresDaily());
        }
        else
        {
            Error();
        }
    }

    public void SubmitHighScore(string username, int score)
    {
        StartCoroutine(AddScore(username, score));
    }

    public void RefreshTopScores()
    {
        StartCoroutine(GetTopScores());
    }

    IEnumerator GetTopScores()
    {
        // Get Lifetime high scores
        string query = TopScoresURL + "?game=" + GameName;
        WWW GetScoresAttempt = new WWW(query);
        yield return GetScoresAttempt;

        if (GetScoresAttempt.error != null)
        {
            Error();
        }
        else
        {
            //Collect up all our data
            string[] textlist = GetScoresAttempt.text.Split(new string[] { "\n", "-" }, System.StringSplitOptions.RemoveEmptyEntries);

            int HighScoreListLength = Mathf.FloorToInt(textlist.Length / 2);

            TopScores.Clear();

            for (int i = 0; i < HighScoreListLength; i++)
            {
                TopScore ts = new TopScore();
                ts.Name = textlist[i*2];
                int.TryParse(textlist[i*2+1], out ts.Score);

                TopScores.Add(ts);
            }
        }

        // Get Daily scores
        query = TopScoresDailyURL + "?game=" + GameName;
        WWW GetDailyScoresAttempt = new WWW(query);
        yield return GetDailyScoresAttempt;

        if (GetDailyScoresAttempt.error != null)
        {
            Error();
        }
        else
        {
            //Collect up all our data
            string[] textlist = GetDailyScoresAttempt.text.Split(new string[] { "\n", "-" }, System.StringSplitOptions.RemoveEmptyEntries);

            int HighScoreListLength = Mathf.FloorToInt(textlist.Length / 2);

            TopScoresDaily.Clear();

            for (int i = 0; i < HighScoreListLength; i++)
            {
                TopScore ts = new TopScore();
                ts.Name = textlist[i * 2];
                int.TryParse(textlist[i * 2 + 1], out ts.Score);

                TopScoresDaily.Add(ts);
            }
        }

        // Done getting scores
        HighScoresUpdated(this);
    }

    void Error()
    {
        print("Error trying to post score");
    }

    // Use this for initialization
    void Start () {
    }

}
