using System.Collections.Generic;
using System.Threading.Tasks;
using Billing.Languages;
using Billing.Models;
using Billing.Store;
using Billing.Themes;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace Billing
{
    public class App : Application
    {
        public static AppTheme CurrentTheme { get; private set; }
        public static PlatformCulture CurrentCulture { get; private set; }
        public static List<Bill> Bills => bills ??= new List<Bill>();
        public static List<Account> Accounts => accounts ??= new List<Account>();
        public static List<Category> Categories => categories ??= new List<Category>();

        private static List<Bill> bills;
        private static List<Account> accounts;
        private static List<Category> categories;

        public App()
        {
            CurrentCulture = new PlatformCulture();
            InitResources();

            MainPage = new MainShell();
            Shell.Current.GoToAsync("//Settings");
        }

        public static void WriteAccounts() => StoreHelper.WriteAccounts(accounts);

        public static void WriteBills() => StoreHelper.WriteBills(bills);

        protected override void OnStart()
        {
            Helper.Debug($"personal folder: {StoreHelper.PersonalFolder}");
            Helper.Debug($"cache folder: {StoreHelper.CacheFolder}");

            accounts = StoreHelper.GetAccounts();
            categories = StoreHelper.GetCategories();
            bills = StoreHelper.GetBills();

            Shell.Current.GoToAsync("//Bills");
        }

        protected override void OnResume()
        {
            SetTheme(AppInfo.RequestedTheme);
        }

        private void InitResources()
        {
            var theme = AppInfo.RequestedTheme;
            SetTheme(theme, true);
        }

        private void SetTheme(AppTheme theme, bool force = false)
        {
            if (force || theme != CurrentTheme)
            {
                CurrentTheme = theme;
            }
            else
            {
                return;
            }
            Helper.Debug($"application theme: {theme}");

            BaseTheme instance;
            if (theme == AppTheme.Dark)
            {
                instance = Dark.Instance;
            }
            else
            {
                instance = Light.Instance;
            }
            // TODO: status bar
            Resources = instance;
        }
    }
}