using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Google;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;

public static class DataManager{
    public const string API_ENDPOINT = "https://vps.playpoolstudios.com/faucet/golf/api/";
    public const string key = "#2CuV1Bit^S!sW1ZcgRv8BhrO";
    public static UserData userData{get; private set;}
    public static List<LeaderboardItemData> Leaderboard{get; private set;}
    public static bool isLogged{ get{return userData != null;}}

    public static void Signout(){
        GoogleSignIn.DefaultInstance.SignOut();
        PlayerPrefs.DeleteAll();
        PlayerPrefs.Save();

        userData = null;
    }


    public static async Task<int> Login(string username,string password){
        WWWForm form = new WWWForm();
        form.AddField("username", username);
        form.AddField("password", password);
        form.AddField("key", key);

    
        
        using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "login.php", form))
        {
            var operation = request.SendWebRequest();
            while (!operation.isDone)
            {
                await Task.Yield();
            }

            Debug.Log("login response: " +request.downloadHandler.text);

            if(request.downloadHandler.text.Contains("{")){
                try{
                    userData = JsonConvert.DeserializeObject<UserData>(request.downloadHandler.text);
                    Debug.Log("Success parsing userdata");

                    PlayerPrefs.SetString("username", username);
                    PlayerPrefs.SetString("password", password);
                    PlayerPrefs.Save();

                }catch(Exception e){
                    Debug.Log("Error parsing userdata");
                }
            }else{
                if(request.downloadHandler.text == "0"){
                    userData = new UserData(){username = username};
                    Debug.Log("Created local account");
                }else{
                    MessageBox.ShowMessage("Error logging in, Server said\n" +request.downloadHandler.text);
                    return 1;
                }
            }
                      
        }

        LoadingScreen.LoadLevel("MainMenu");
        return 0;

    }

    public static async Task<int> LinkFH(string fhid){
        WWWForm form = new WWWForm();
        form.AddField("username", userData.username);
        form.AddField("fhid", fhid);
        form.AddField("key", key);

    
        using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "link_fh.php", form))
        {
            var operation = request.SendWebRequest();
            while (!operation.isDone)
            {
                await Task.Yield();
            }

            Debug.Log("fh link response: " +request.downloadHandler.text);

            if(request.downloadHandler.text== "0"){
                userData.faucetId = int.Parse(fhid);
                Debug.Log("FH Link success");
            }
                      
        }

        return 0;

    }

    public static async void GoogleLogin(string username){
        WWWForm form = new WWWForm();
        form.AddField("username", username);
        form.AddField("key", key);

       using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "google_login.php", form))
        {
            var operation = request.SendWebRequest();
            while (!operation.isDone)
            {
                await Task.Yield();
            }
            Debug.Log("glogin response: " +request.downloadHandler.text);
            // MessageBox.ShowMessage(request.downloadHandler.text);

            if(request.downloadHandler.text.Contains("{")){
                try{
                    userData = JsonConvert.DeserializeObject<UserData>(request.downloadHandler.text);
                    if(userData == null){
                        throw new NullReferenceException();
                    }
                    if(userData.username.Length < 3){
                        throw new IndexOutOfRangeException();
                    }
                    Debug.Log("Success parsing userdata");
                    
                    PlayerPrefs.SetString("username", username + "#0");
                    PlayerPrefs.SetString("password", username+ "#0");
                    PlayerPrefs.Save();
                }catch(Exception e){
                    Debug.Log("Error parsing userdata");
                }
            }else{
                if(request.downloadHandler.text == "0"){
                    userData = new UserData(){username = username + "#0"};
                }else{
                    MessageBox.ShowMessage("Error logging in, Server said\n" +request.downloadHandler.text);
                    return;
                }
            }
                      
        }

        LoadingScreen.LoadLevel("MainMenu");
    }

    public static async void AddScores(int amount){
        WWWForm form = new WWWForm();

        Debug.Log(userData.ToString());

        form.AddField("username", userData.username);
        form.AddField("password", userData.password);
        form.AddField("amount", amount);
        form.AddField("key", key);

       using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "add_scores.php", form))
        {
            var operation = request.SendWebRequest();
            while (!operation.isDone)
            {
                await Task.Yield();
            }
            Debug.Log("add scores response: " +request.downloadHandler.text);
            
            if(request.downloadHandler.text.Contains("{")){
                try{
                    userData = JsonConvert.DeserializeObject<UserData>(request.downloadHandler.text);
                    if(userData == null){
                        throw new NullReferenceException();
                    }
                    if(userData.username.Length < 3){
                        throw new IndexOutOfRangeException();
                    }
                    Debug.Log("Success parsing userdata");


                }catch(Exception e){
                    Debug.Log("Error parsing userdata");
                }
            }else{
                
                MessageBox.ShowMessage("Error Updating scores, Server said\n" +request.downloadHandler.text);
                
            }
                      
        }

        LoadingScreen.LoadLevel("MainMenu");
    }

    public static async void AddHoleInOne(){
        WWWForm form = new WWWForm();

        Debug.Log(userData.ToString());

        form.AddField("username", userData.username);
        form.AddField("password", userData.password);
        form.AddField("key", key);

       using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "add_hole_in_one.php", form))
        {
            var operation = request.SendWebRequest();
            while (!operation.isDone)
            {
                await Task.Yield();
            }
            Debug.Log("add hole in one response: " +request.downloadHandler.text);
            
            if(request.downloadHandler.text.Contains("{")){
                try{
                    userData = JsonConvert.DeserializeObject<UserData>(request.downloadHandler.text);
                    if(userData == null){
                        throw new NullReferenceException();
                    }
                    if(userData.username.Length < 3){
                        throw new IndexOutOfRangeException();
                    }
                    Debug.Log("Success parsing userdata");


                }catch(Exception e){
                    Debug.Log("Error parsing userdata");
                }
            }else{
                
                MessageBox.ShowMessage("Error Updating hole in ones, Server said\n" +request.downloadHandler.text);
                
            }
                      
        }

        // LoadingScreen.LoadLevel("MainMenu");
    }

     public static async void AddAdImpression(){
        WWWForm form = new WWWForm();

        Debug.Log(userData.ToString());

        form.AddField("username", userData.username);
        form.AddField("password", userData.password);
        form.AddField("key", key);

       using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "add_impression.php", form))
        {
            var operation = request.SendWebRequest();
            while (!operation.isDone)
            {
                await Task.Yield();
            }
            Debug.Log("add ad impression response: " +request.downloadHandler.text);
            
            if(request.downloadHandler.text.Contains("{")){
                try{
                    userData = JsonConvert.DeserializeObject<UserData>(request.downloadHandler.text);
                    if(userData == null){
                        throw new NullReferenceException();
                    }
                    if(userData.username.Length < 3){
                        throw new IndexOutOfRangeException();
                    }
                    Debug.Log("Success parsing userdata");


                }catch(Exception e){
                    Debug.Log("Error parsing userdata");
                }
            }else{
                
                MessageBox.ShowMessage("Error Updating add_impression, Server said\n" +request.downloadHandler.text);
                
            }
                      
        }

        // LoadingScreen.LoadLevel("MainMenu");
    }

    public static async Task RefreshLeaderboard(bool total = false){
        WWWForm form = new WWWForm();

        Debug.Log(userData.ToString());
        form.AddField("username", userData.username);
        if(total){
            form.AddField("total", "1");
        }
        bool foundMe = false;

        using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "get_leaderboard.php", form))
        {
            var operation = request.SendWebRequest();
            while (!operation.isDone)
            {
                await Task.Yield();
            }
            Debug.Log("leaderboard response: " +request.downloadHandler.text);
            if(request.downloadHandler.text.Contains("{")){
                try{
                    string[] items = request.downloadHandler.text.Split("<td>");
                    Leaderboard = new List<LeaderboardItemData>();
                    foreach(string item in items){
                        if(item == DataManager.userData.username){
                            foundMe=true;
                        }
                        LeaderboardItemData newItem = JsonConvert.DeserializeObject<LeaderboardItemData>(item);
                        Leaderboard.Add(newItem);
                    }
                    Debug.Log("Success parsing userdata");
                }catch(Exception e){
                    Debug.Log("Error parsing leaderboard");
                }
            }else{                
                MessageBox.ShowMessage("Error getting leaderboard, Server said\n" +request.downloadHandler.text);                
            }                    
        }

        if(!foundMe){
            form.AddField("id",DataManager.userData.id);
            form.AddField("topScore","1");
            
            using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "get_player_position.php", form))
            {
                var operation = request.SendWebRequest();
                while (!operation.isDone)
                {
                    await Task.Yield();
                }
                Debug.Log("my position: " +request.downloadHandler.text);

                LeaderboardItemData newItem = new LeaderboardItemData(){position=int.Parse(request.downloadHandler.text), name= DataManager.userData.username, topScore = DataManager.userData.TopScore, Score = DataManager.userData.score};
                Leaderboard.Add(newItem);
            }
        }
    }


}

[System.Serializable]
public class UserData{
    public int id;
    public string username;
    public string password;
    public int score;
    public int TopScore;
    public int faucetId;


    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
}

[System.Serializable]
public class LeaderboardItemData{
    public int position;
    public string name;
    public int topScore;

    public int Score;

    public string DisplayName{get{
        string _name= name;
        if(name.Contains("#0")){
            _name = _name.Substring(0,name.IndexOf("@gmail"));
        }

        return _name;
    }}
}
