/*
“Commons Clause” License Condition v1.0
https://commonsclause.com/

The Software is provided to you by the Licensor under the License, as defined below, subject to the following condition.

Without limiting other conditions in the License, the grant of rights under the License will not include, and the License does not grant to you, the right to Sell the Software.

For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you under the License to provide to third parties, for a fee or other consideration (including without limitation fees for hosting or consulting/ support services related to the Software), a product or service whose value derives, entirely or substantially, from the functionality of the Software. Any license notice or attribution required by the License must also include this Commons Clause License Condition notice.

Software: Open Archival

License: GNU GPL: https://www.gnu.org/licenses/gpl-3.0.en.html

Licensor: Vincent Allen
*/

namespace OpenArchival.Blazor;

using global::OpenArchival.DataAccess;
using Microsoft.EntityFrameworkCore;
using MudBlazor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

public enum BlogSearchFilterType
{
    All,
    Title,
    Content,
    Tags,
}

public class BlogPostSearch
{
    public int TotalResults { get; set; }

    public int TotalPages { get; set; }

    public int PageSize { get; set; } = 20;

    public int CurrentPage { get; set; } = 1;

    public List<BlogPost> SearchResults { get; set; } = [];

    private string _searchTerms { get; set; }

    private IDbContextFactory<ApplicationDbContext> _contextFactory { get; set; }

    private Expression<Func<BlogPost, bool>> _currentFilterPredicate;

    private BlogSearchFilterType _selectedFilter = BlogSearchFilterType.All;

    public BlogPostSearch(IDbContextFactory<ApplicationDbContext> contextFactory)
    {
        _contextFactory = contextFactory;
    }

    public async Task Search(string Terms, BlogSearchFilterType filter, int page = 1)
    {
        _searchTerms = Terms;
        _selectedFilter = filter;

        if (string.IsNullOrEmpty(_searchTerms))
        {
            await using var context = await _contextFactory.CreateDbContextAsync();
            TotalResults = await context.BlogPosts.CountAsync();
;
            TotalPages = (int)Math.Ceiling(TotalResults / (double)PageSize);
        }
        else
        {
            // Determine which filter expression to use based on the radio button selection
            switch (_selectedFilter)
            {
                case BlogSearchFilterType.Tags:
                    _currentFilterPredicate = x => x.TagsSearchVector.Matches(_searchTerms);
                    break;

                case BlogSearchFilterType.Title:
                    _currentFilterPredicate = x => x.TitleSearchVector.Matches(_searchTerms);
                    break;

                case BlogSearchFilterType.Content:
                    _currentFilterPredicate = x => x.ContentSearchVector.Matches(_searchTerms);
                    break;

                case BlogSearchFilterType.All:
                default:
                    _currentFilterPredicate = x => x.AllSearchVector.Matches(_searchTerms);
                    break;
            }

            // Get the total count using the chosen filter
            await using var context = await _contextFactory.CreateDbContextAsync();
            TotalResults = await context.BlogPosts.Where(_currentFilterPredicate).CountAsync();
            TotalPages = (int)Math.Ceiling(TotalResults / (double)PageSize);
        }
        // Load the first page with the chosen filter
        await LoadPageAsync(page);
    }

    public async Task LoadPageAsync(int page)
    {
        CurrentPage = page;

        await using var context = await _contextFactory.CreateDbContextAsync();
        if (string.IsNullOrEmpty(_searchTerms))
        {
            SearchResults = await context.BlogPosts
                .OrderByDescending(post => post.CreationTime)
                .Include(p => p.ArtifactGroupings)
                .Include(p => p.MainPhoto)
                .Skip((CurrentPage - 1) * PageSize)
                .Take(PageSize)
                .ToListAsync();
        }
        else
        {
            SearchResults = await context.BlogPosts.Where(_currentFilterPredicate)
                .Include(p => p.ArtifactGroupings)
                .Include(p => p.MainPhoto)
                .OrderBy(p => p.Id)
                .Skip((CurrentPage - 1) * PageSize)
                .Take(PageSize)
                .ToListAsync();
        }
    }

    public void ClearResults()
    {
        SearchResults.Clear();
        TotalResults = 0;
        TotalPages = 0;
    }
}