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

public class HomeMissions : MonoBehaviour{
    public GameObject Home_missionContainer; // Reference to the Character_Selection canvas
    public GameObject Home_missionPrefab; // Mission prefab

    private const string player_missionData = "Player_MissionData";

    [HideInInspector]
    public MissionProgress missionProgress;

    [HideInInspector]
    public List<MissionInfo> missionsInWeek;

    Missions mission_details;


    void OnEnable(){
        if (PlayerPrefs.HasKey(player_missionData)){
            missionProgress = LoadPlayer_MissionData();
        }

        mission_details = GetComponent<Missions>();
        missionsInWeek = mission_details.getWeeklyMissions(missionProgress.current_week);

        string result1 = ListToString(missionsInWeek);
        //Debug.Log("Missions = " + result1);


        foreach (MissionInfo mission_info in missionsInWeek){
            // Instantiate the mission prefab
            GameObject homeMission_instance = Instantiate(Home_missionPrefab, Home_missionContainer.transform);
            homeMission_instance.name = "homeMission";

            TextMeshProUGUI homeMissionTitle = homeMission_instance.transform.Find("missionDetails").GetComponent<TextMeshProUGUI>();
            homeMissionTitle.text = mission_info.missionTitle;

            TextMeshProUGUI homeMissionXP = homeMission_instance.transform.Find("missionXP").GetComponent<TextMeshProUGUI>();
            homeMissionXP.text = "+ " + (mission_info.missionXP).ToString() + " XP";

        }

        Home_missionPrefab.SetActive (false);
    }


    string ListToString<T>(List<T> list){
        // Use string.Join to concatenate the elements of the list into a string
        return string.Join(", ", list);
    }


    //Loads mission progress from PlayerPrefs.
    MissionProgress LoadPlayer_MissionData(){
        string jsonData = PlayerPrefs.GetString(player_missionData, "{}"); // Details were stored as "PlayerData"
        return JsonUtility.FromJson<MissionProgress>(jsonData);
    }


    // Start is called before the first frame update
    void Start(){
        
    }

    // Update is called once per frame
    void Update(){
        
    }
}
