using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using tytdemail.Model;
using Tesses.YouTubeDownloader.MailKit;
using Tesses.YouTubeDownloader;

namespace tytdemail.Pages;

public class IndexModel : PageModel
{
    [Microsoft.AspNetCore.Components.Inject]
    public IConfiguration? Configuration {get;set;}
    [BindProperty]
    public string Ids {get;set;}="";

   

    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    public void OnGet()
    {
        try{
            config=Configuration.GetValue<SMTPConfig>("SMTP");
        }catch(Exception ex)
        {
            _=ex;
        }
    }
    private SMTPConfig? config;

    public bool ConfigNull 
    {
        get{return config == null;}
    }
    public string Email {get{
        if(config==null || string.IsNullOrWhiteSpace(config.ToEmail))
        {
            return "tytd@tesses.net";
        }
        return config.ToEmail;
    }}
    public async Task<IActionResult> OnPostAsync()
    {
        try{
        config=Configuration.GetValue<SMTPConfig>("SMTP");
        }catch(Exception ex)
        {
            _=ex;
        }
        if(ModelState.IsValid && config != null)
        {
            
            
            if(!string.IsNullOrWhiteSpace(config.SmtpServer) && !string.IsNullOrWhiteSpace(config.Username) && !string.IsNullOrWhiteSpace(config.Password) && !string.IsNullOrWhiteSpace(config.FromEmail))
            {
            SMTPDownloader downloader = new SMTPDownloader(config.SmtpServer,config.FromEmail,Email,config.Username,config.Password,config.SmtpPort,config.SecureOption);
            foreach(var item in Ids.Split(new char[]{'\r','\n'}))
            {
                await downloader.AddItemAsync(item);
            }
            }
        }
        Ids="";
        return RedirectToPage("Index");
    }
}
