using Nickvision.Desktop.Application;
using Nickvision.Desktop.Globalization;
using Nickvision.Parabolic.Shared.Models;
using Nickvision.Parabolic.Shared.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Nickvision.Parabolic.Shared.Controllers;

public class HistoryViewController
{
    private readonly IEventsService _eventsService;
    private readonly IHistoryService _historyService;
    private readonly ITranslationService _translationService;

    public IReadOnlyList<SelectionItem<HistoryLength>> Lengths { get; }

    public HistoryViewController(IEventsService eventsService, IHistoryService historyService, ITranslationService translationService)
    {
        _eventsService = eventsService;
        _historyService = historyService;
        _translationService = translationService;
        var selectedLength = _historyService.Length;
        Lengths = new List<SelectionItem<HistoryLength>>
        {
            new SelectionItem<HistoryLength>(HistoryLength.Never, _translationService._("Never"), selectedLength == HistoryLength.Never),
            new SelectionItem<HistoryLength>(HistoryLength.OneDay, _translationService._("1 Day"), selectedLength == HistoryLength.OneDay),
            new SelectionItem<HistoryLength>(HistoryLength.OneWeek, _translationService._("1 Week"), selectedLength == HistoryLength.OneWeek),
            new SelectionItem<HistoryLength>(HistoryLength.OneMonth, _translationService._("1 Month"), selectedLength == HistoryLength.OneMonth),
            new SelectionItem<HistoryLength>(HistoryLength.ThreeMonths, _translationService._("3 Months"), selectedLength == HistoryLength.ThreeMonths),
            new SelectionItem<HistoryLength>(HistoryLength.SixMonths, _translationService._("6 Months"), selectedLength == HistoryLength.SixMonths),
            new SelectionItem<HistoryLength>(HistoryLength.OneYear, _translationService._("1 Year"), selectedLength == HistoryLength.OneYear),
            new SelectionItem<HistoryLength>(HistoryLength.Forever, _translationService._("Forever"), selectedLength == HistoryLength.Forever)
        };
    }

    public bool SortNewest
    {
        get => _historyService.SortNewest;

        set => _historyService.SortNewest = value;
    }

    public HistoryLength Length
    {
        set => _historyService.Length = value;
    }

    public Task ClearAllAsync() => _historyService.ClearAsync();

    public async Task<IReadOnlyList<SelectionItem<HistoricDownload>>> GetAllAsync()
    {
        var result = new List<SelectionItem<HistoricDownload>>();
        foreach (var download in await _historyService.GetAllAsync())
        {
            result.Add(new SelectionItem<HistoricDownload>(download, download.Title, false));
        }
        return result;
    }

    public Task RemoveAsync(Uri url) => _historyService.RemoveAsync(url);

    public void RequestDownload(Uri url) => _eventsService.InvokeDownloadRequested(url);
}
