using System;
using System.IO;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media.Imaging;
using System.Linq;
using Avalonia.Platform.Storage;
using demko_v.Models;

namespace demko_v;

public partial class AddAgentWindow : Window
{
    
    public string PathToImage = string.Empty;
    
    public AddAgentWindow()
    {
        InitializeComponent();
    }
    
    private async Task<Bitmap?> SelectAndSaveImage()
    {
        var showDialog = StorageProvider.OpenFilePickerAsync(
            options: new Avalonia.Platform.Storage.FilePickerOpenOptions()
            {
                Title = "Select an image",
                FileTypeFilter = new[] { FilePickerFileTypes.ImageAll }
            });
        var storageFile = await showDialog;
        try
        {
            var bmp = new Bitmap(storageFile.First().TryGetLocalPath());
            string shortGuid = Guid.NewGuid().ToString("N").Substring(0, 8);
            string path = $"/Users/feitanportor/dev/C#/demko_v/demko_v/bin/Debug/net8.0/agents/{shortGuid}.jpg";
            bmp.Save(path);
            PathToImage = path;
            return bmp;
        }
        catch
        {
            return null;
        }
    }

    public void AddAgent_OnClick(object? sender, RoutedEventArgs e)
    {
        using var ctx = new DemoAgentsContext();

        if (string.IsNullOrWhiteSpace(TitleTextBox.Text) ||
            string.IsNullOrWhiteSpace(AddressTextBox.Text) ||
            string.IsNullOrWhiteSpace(InnTextBox.Text) ||
            string.IsNullOrWhiteSpace(KppTextBox.Text) ||
            string.IsNullOrWhiteSpace(PriorityTextBox.Text) ||
            string.IsNullOrWhiteSpace(EmailTextBox.Text) ||
            string.IsNullOrWhiteSpace(PhoneNumberTextBox.Text) ||
            string.IsNullOrWhiteSpace(PathToImage))
        {
            return;
        }

        if (TypeAgentAddCombobox.SelectedItem is not ComboBoxItem selectedItem)
            return;

        string selectedType = selectedItem.Content.ToString();
        
        var agentType = ctx.AgentTypes.FirstOrDefault(at => at.Title == selectedType);
        if (agentType is null)
        {
            return;
        }

        var newAgent = new Agent
        {
            Title = TitleTextBox.Text,
            Address = AddressTextBox.Text,
            Inn = InnTextBox.Text,
            Kpp = KppTextBox.Text,
            Priority = int.Parse(PriorityTextBox.Text),
            Email = EmailTextBox.Text,
            Phone = PhoneNumberTextBox.Text,
            Logo = PathToImage,
            DirectorName = DirectorNameTextBox.Text,
            AgentTypeId = agentType.Id
        };

        ctx.Agents.Add(newAgent);
        ctx.SaveChanges();

        Close();
    }

    private async void SelectImage(object? sender, RoutedEventArgs e)
    {
        AgentImage.Source = await SelectAndSaveImage();
    }
}