using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HyperCube.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Console = HyperCube.Utils.AdvConsole;

namespace HyperCube
{
    /// <summary>
    /// Синглтон приложения
    /// </summary>
    public class AppData
    {
        public ReportModel Report { get; set; } = new();
        public AccountModel CurrentAccount { get; set; }
        public ArticleModel CurrentArticle { get; set; }
        public ArticleModel CurrentArticleClone { get; set; }

        private static Dictionary<int, ArticleModel> _articles;
        public static Dictionary<int, ArticleModel> Articles
        {
            get
            {
                if (_articles == null)
                    LoadArticles();
                return _articles;
            }
        }

        public static async Task LoadArticles()
        {
            Console.WriteLine("GetArticles()");

            MySQLConnector dbCon = MySQLConnector.Instance();

            string stringSQL = $"SELECT a.id, filename, article_name, date_publish, authors, ah.action_type " +
                    $"FROM articles a " +
                    $"LEFT JOIN actions_history ah ON a.id = ah.article_id " +
                    $"AND EXISTS (SELECT 1 FROM actions_history ah1 WHERE ah.article_id = ah1.article_id HAVING MAX(ah1.date_add) = ah.date_add) " +
                    $"ORDER BY a.id";
            _articles = await dbCon.SQLSelectArticles(stringSQL);
        }
    }
}
