using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TodoDetails.Model;

namespace TodoDetails.Services
{
    public class TodoService
    {
        Lazy<Task<List<Todo>>> todoList;

        public TodoService()
        {
            todoList = new Lazy<Task<List<Todo>>>(
                async () =>
                {
                    List<Todo>? result = null;

                    using var stream = await FileSystem.OpenAppPackageFileAsync("tododata.json");
                    using var reader = new StreamReader(stream);
                    var contents = await reader.ReadToEndAsync();

                    if (contents != null)
                    {
                        result = JsonSerializer.Deserialize<List<Todo>>(contents);
                    }

                    return result ?? new();
                });
        }

        public async Task<List<Todo>> GetTodos()
        {
            return await todoList.Value;
        }
    }
}