using Newtonsoft.Json;
using System;
using System.IO;
using UnityEngine;

[CreateAssetMenu(fileName = "profile", menuName = "Profile")]
public sealed class Profile : ScriptableObject
{
    [SerializeField]
    private string savePath = "user.sav";
    [SerializeField]
    private StarMapGenerator generator = null;

    private string FullSavePath => Path.Combine(Application.persistentDataPath, savePath);

    [NonSerialized]
    private Player player = null;
    public Player Player => LoadDefaultPlayer();
    public Player SavedPlayer => player;

    private Player LoadDefaultPlayer()
    {
        if (player == null)
        {
            LoadPlayer();
        }
        if (player == null)
        {
            CreateNewPlayer();
            Debug.Log("Create player " + player.NavigationPoints.Length);
            SavePlayer();
        }
        return player;
    }

    public void LoadPlayer()
    {
        try
        {
            if (File.Exists(FullSavePath))
            {
                var playerData = JsonConvert.DeserializeObject<PlayerData>(File.ReadAllText(FullSavePath));
                player = PlayerLoader.LoadPlayer(playerData, generator);
                Debug.Log($"Load player from {FullSavePath}");
            }
            else
            {
                Debug.Log("No save file");
            }
        }
        catch (Exception e)
        {
            Debug.LogError(e.Message);
        }
    }

    public void SavePlayer()
    {
        if (player == null)
            return;

        File.WriteAllText(FullSavePath, JsonConvert.SerializeObject(PlayerLoader.SavePlayer(player)));
        Debug.Log($"Save file to {FullSavePath}");
    }

    public void CreateNewPlayer()
    {
        var data = generator.CreatePlayer();
        player = PlayerLoader.LoadPlayer(data, generator);
    }

    [ContextMenu("clear_player")]
    public void ClearPlayer()
    {
        player = null;
        if (File.Exists(FullSavePath))
        {
            File.Delete(FullSavePath);
            Debug.Log($"Deleted player file: {FullSavePath}");
        }
    }
}
