using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using System;
using TMPro;
using GooglePlayGames.BasicApi.SavedGame;
using scripts;


public class PlayGamesManager : MonoBehaviour
{
    [SerializeField]
    TMP_Text nicknameText;

    private score score;

    [SerializeField]
    private shopManager shopManager;

    [SerializeField]
    private MenuControler menuController;

    [SerializeField]
    private TMP_Text debugText;

    [SerializeField]
    private GameObject LoadingUI;


    // Start is called before the first frame update
    void Start()
    {
        this.score = GetComponent<score>();

        SignIn();
    }

    #region signin

    public void SignIn()
    {
        PlayGamesPlatform.Activate();
        PlayGamesPlatform.Instance.Authenticate(ProcessAuthentication);
    }

    internal void ProcessAuthentication(SignInStatus status)
    {
        if (status == SignInStatus.Success)
        {
            // Continue with Play Games Services

            string name = PlayGamesPlatform.Instance.GetUserDisplayName();

            nicknameText.text = name;

            menuController.ShowSignInUI(false);

            OpenSave(false);
        }
        else
        {
            menuController.ShowSignInUI(true);

            // Disable your integration with Play Games Services or show a login button
            // to ask users to sign-in. Clicking it should call
            // PlayGamesPlatform.Instance.ManuallyAuthenticate(ProcessAuthentication).
        }
    }

    public void ManualAuthentication()
    {
        PlayGamesPlatform.Instance.ManuallyAuthenticate(ProcessAuthentication);

        menuController.ShowSignInUI(false);

        OpenSave(false);
    }

    #endregion

    #region save

    private bool isSaving;

    public void OpenSave(bool saving)
    {
        if (Social.localUser.authenticated)
        {
            isSaving = saving;
            ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution("Save", DataSource.ReadCacheOrNetwork, ConflictResolutionStrategy.UseLongestPlaytime, SavedGameOpen);
        }
    }

    private void SavedGameOpen(SavedGameRequestStatus status, ISavedGameMetadata metadata)
    {
        if (status == SavedGameRequestStatus.Success)
        {
            debugText.text += "Request successfull!\n";

            if (isSaving)    //  Saving
            {
                debugText.text += "Saving...\n";

                byte[] myData = System.Text.ASCIIEncoding.ASCII.GetBytes(GetSaveString());

                SavedGameMetadataUpdate updateForMetadata = new SavedGameMetadataUpdate.Builder().WithUpdatedDescription("I have played my game at: " + DateTime.Now.ToString()).Build();

                ((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(metadata, updateForMetadata, myData, SaveCallback);

                debugText.text += "Saving...\n";
            }
            else    //  Loading
            {
                debugText.text += "loading...\n";

                ((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(metadata, LoadCallBack);
            }
        }
        else
        {
            debugText.text += "Request failed!\n";
        }
    }

    private void LoadCallBack(SavedGameRequestStatus status, byte[] data)
    {
        if (status == SavedGameRequestStatus.Success)
        {
            debugText.text += "Load request successfull!\n";

            string loadedData = System.Text.ASCIIEncoding.ASCII.GetString(data);

            LoadSavedString(loadedData);

            debugText.text += "Data loaded!\n";

            ShowLoadingUI(false);
        }
        else
        {
            debugText.text += "Load request failed!\n";

            ShowLoadingUI(false);

            menuController.ShowSignInUI(true);
        }
    }

    private void LoadSavedString(string loadedData)
    {
        int highscore = 0;

        int coins = 0;

        string ownedPlanes = "0";

        if (loadedData.Length > 0)
        {
            string[] cloudStringArr = loadedData.Split('|');

            highscore = int.Parse(cloudStringArr[0]);

            coins = int.Parse(cloudStringArr[1]);

            ownedPlanes = cloudStringArr[2];
            
        }

        score.SetHighscore(highscore);

        shopManager.coins = coins;

        shopManager.ConvertOwnedPlanes(ownedPlanes);
    }

    private string GetSaveString()
    {
        string dataToSave = "";

        dataToSave += ((int)score.highscoreAmount).ToString() + "|" + shopManager.coins.ToString() + "|" + shopManager.GetOwnedPlanesString();

        return dataToSave;
    }

    private void SaveCallback(SavedGameRequestStatus status, ISavedGameMetadata metadata)
    {
        if (status == SavedGameRequestStatus.Success)
        {
            Debug.Log("Successfully saved to the cloud\n");

            debugText.text += "Successfully saved to the cloud!\n";
        }
        else
        {
            Debug.Log("Failed to save to cloud\n");

            debugText.text += "Failed to save to cloud!\n";
        }
    }

    private void ShowLoadingUI(bool show)
    {
        LoadingUI.SetActive(show);
    }

    #endregion

    #region achievements

    public void ShowAchievementsPanel()
    {
        Social.ShowAchievementsUI();
    }

    public void UnlockAchievement(String achievement)
    {
        switch(achievement)
        {
            case "on_fire":
                Social.ReportProgress(PlaneRunGPGSIds.achievement_on_fire, 100f, null);
                break;
            case "warming_up":
                Social.ReportProgress(PlaneRunGPGSIds.achievement_warming_up, 100f, null);
                break;
            case "untouchable":
                Social.ReportProgress(PlaneRunGPGSIds.achievement_untouchable, 100f, null);
                break;
        }
    }

    #endregion

    #region leaderboard

    public void ShowLeaderboard()
    {
        Social.ShowLeaderboardUI();
    }

    public void UpdateLeaderboardScore(int score)
    {
        Social.ReportScore(score, PlaneRunGPGSIds.leaderboard_highscore, null);
    }

    #endregion
}