using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AppLibs.Libs
{
    public class WSNavigation
    {
        private static List<NavItem> list = new List<NavItem>() ;
        private static readonly object loadLock = new object();
        private static Task? t;

        public static async Task LoadJson()
        {
            lock (loadLock)
            {
                // Nếu đang có task load cũ chưa xong, có thể đợi hoặc hủy (tùy logic)
                if (t != null && !t.IsCompleted)
                    return;

                t = LoadNavItem();
            }
            await t.ConfigureAwait(false);
        }

        static async Task LoadNavItem()
        {
            var newList = new List<NavItem>();
            using (var reader = new StreamReader(Path.GetFullPath("Json/navlist.json")))
            {
                string json = await reader.ReadToEndAsync().ConfigureAwait(false);
                var deserializedList = JsonConvert.DeserializeObject<List<NavItem>>(json);
                if (deserializedList != null)
                {
                    newList = deserializedList;
                }
            }
            System.Threading.Interlocked.Exchange(ref list, newList);
        }
        public static async Task<List<NavItem>> GetListMenu()
        {
            if (t != null)
            {
                if (!t.IsCompleted)
                {
                    await t;
                } 
            }
            return list;
        }
    }
}
