using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using PhilExample.Interfaces;
using PhilExampleCrawler.Common.Models;
using Xamarin.Essentials;

namespace PhilExample.Services
{
    internal class PhExStorage : IPhExStorage
    {
        const string CATEGORIES = "CATS";
        const string RADII = "RADS";

        public async Task<bool> SaveCategoriesAsync(IEnumerable<Category> cats)
        {
            try
            {
                await SecureStorage.SetAsync(CATEGORIES, JsonConvert.SerializeObject(cats));
                return true;
            }
            catch (Exception ex)
            {
                //TODO: LOG
            }
            return false;
        }

        public async Task<IEnumerable<Category>> GetCategoriesAsync()
        {
            try
            {
                string catsJson = await SecureStorage.GetAsync(CATEGORIES);
                if (!string.IsNullOrEmpty(catsJson))
                    return JsonConvert.DeserializeObject<IEnumerable<Category>>(catsJson) 
                        ?? new List<Category>();
            }
            catch (Exception ex)
            {
                //TODO: LOG
            }
            return new List<Category>();
        }

        public async Task<bool> SaveRadiiAsync(IEnumerable<Category> radii)
        {
            try
            {
                await SecureStorage.SetAsync(RADII, JsonConvert.SerializeObject(radii));
                return true;
            }
            catch (Exception ex)
            {
                //TODO: LOG
            }
            return false;
        }

        public async Task<IEnumerable<Category>> GetRadiiAsync()
        {
            try
            {
                string radsJson = await SecureStorage.GetAsync(RADII);
                if (!string.IsNullOrEmpty(radsJson))
                    return JsonConvert.DeserializeObject<IEnumerable<Category>>(radsJson)
                        ?? new List<Category>();
            }
            catch (Exception ex)
            {
                //TODO: LOG
            }
            return new List<Category>();
        }
    }
}
