using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class ProfileScreen : MonoBehaviour
{
    public LevelSystem levelSystem;
    public TextMeshProUGUI levelText;
    public TextMeshProUGUI xpText;

    public Image profilePhoto;
    public Button changePhotoButton;

    public Slider xpSlider;

   
   

    private void Start()
    {
        UpdateLevelDisplay();
        changePhotoButton.onClick.AddListener(ChangePhotoButtonClick);
        LoadProfilePhoto();
    }

    private void UpdateLevelDisplay()
    {
        int currentLevel = levelSystem.GetCurrentLevel();
        int currentXP = levelSystem.GetCurrentXP();
        int totalXP = levelSystem.GetTotalXPNeededForLevel(currentLevel);

        RankSystem rankSystem = new RankSystem();
        rankSystem.GetRank(currentLevel);
        Debug.Log("Player Rank: " + rankSystem.GetRank(currentLevel));

        levelText.text = "Level " + currentLevel.ToString();
        xpText.text = currentXP.ToString() + "/" + totalXP.ToString();
        xpSlider.maxValue = totalXP;
        xpSlider.value = currentXP;
    }

    public void ChangePhotoButtonClick()
    {
        // Open a file browser to let the user select an image file
    #if UNITY_EDITOR
        string path = UnityEditor.EditorUtility.OpenFilePanel("Select Profile Photo", "", "png,jpg,jpeg");

        // Load the image into a texture
        byte[] fileData = System.IO.File.ReadAllBytes(path);
        Texture2D texture = new Texture2D(2, 2);
        texture.LoadImage(fileData);

        // Set the profile photo to the loaded texture
        profilePhoto.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));

        // Save the image to a file on disk
        string savePath = Application.persistentDataPath + "/profile_photo.png";
        System.IO.File.WriteAllBytes(savePath, fileData);
    #endif
    }

    private void LoadProfilePhoto()
    {
        string path = Application.persistentDataPath + "/profile_photo.png";
        if (System.IO.File.Exists(path))
        {
            byte[] fileData = System.IO.File.ReadAllBytes(path);
            Texture2D texture = new Texture2D(2, 2);
            texture.LoadImage(fileData);
            profilePhoto.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
        }
    }

}

