using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;
using MercatorApi;
using MercatorExtensions;
using MercatorUi;
using MercatorDatabase;
using System.Windows.Forms;
using System.Threading.Tasks;

namespace SigCli
{
    public class Customizer : MercatorUi.ICustomizers.IFormValidateCustomizer
    {
        public bool FormValidateCustomize(Form form)
        {
            MercatorUi.Forms.Sig.SigForm sigForm = (MercatorUi.Forms.Sig.SigForm)form;
            
            if ((string.IsNullOrWhiteSpace(sigForm.CliRecord.C_PAYS))
            || sigForm.CliRecord.C_PAYS.StartsWith("BE", StringComparison.InvariantCultureIgnoreCase))
            {
                 // Moet een klant uit België te zijn
                if (string.IsNullOrWhiteSpace(sigForm.CliRecord.C_CODEP))
                {
                    Dialogs.Stop("De postcode is leeg");
                    var textBoxCp = sigForm.MovableControls.Values.OfType<MercatorUi.MovableControls.MovableTextBox>()
                                                .Where(p => p.Source == "C_CODEP").FirstOrDefault();
                    if (textBoxCp != null)
                        MercatorUi._Divers.FocusError(textBoxCp);
                    return false;
                }
                var task = Task.Run(async () =>
                    await MercatorController.xFunctions.xAddressesStreetsByPostalCode(MercatorUi.Globals.Langue, sigForm.CliRecord.C_CODEP));
                var allStreetsByPostalCodeRecords = task.Result;
                if (allStreetsByPostalCodeRecords == null)
                {
                    MercatorUi.Dialogs.Stop("Error bij ophalen van straten: "
                                + (MercatorController.xFunctions.xAddressesLastError ?? "erreur inconnue")
                                + "\r\n Onmogelijk om gegevens na te kijken!");
                }
                else
                {
                    string adresse = sigForm.CliRecord.C_ADRESSE;
                    if (!allStreetsByPostalCodeRecords.Where(p => adresse.StartsWith(p.street, StringComparison.InvariantCultureIgnoreCase)).Any()
                        && !Dialogs.AnswerYesNo($"De straat \"{adresse}\" lijkt niet te bestaan.\r\nVerdergaan?"))
                    {
                        var textBoxAd = sigForm.MovableControls.Values.OfType<MercatorUi.MovableControls.MovableTextBox>()
                                                   .Where(p => p.Source == "C_ADRESSE").FirstOrDefault();
                        if (textBoxAd != null)
                            MercatorUi._Divers.FocusError(textBoxAd);
                        return false;
                    }
                }
            }
            return true;
        }

    }
}