using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Windows.Forms;
using MercatorApi;
using MercatorExtensions;


namespace Billing
{
    public class Customizer : MercatorUi.ICustomizers.IBillingEngineCreated, MercatorUi.ICustomizers.IBillingEngineClosed
    {
        public void BillingEngineCreated(MercatorUi.Engine.Gescom.BillingEngine billingEngine)
        {
            billingEngine.BeforeSendMail += BillingEngine_BeforeSendMail;
        }

        public void BillingEngineClosed(MercatorUi.Engine.Gescom.BillingEngine billingEngine)
        {
            billingEngine.BeforeSendMail -= BillingEngine_BeforeSendMail;
        }

        void BillingEngine_BeforeSendMail(object sender, MercatorUi.Engine.Gescom.BillingEngine.BeforeSendMailEventArgs e)
        {
            MercatorUi.Engine.Gescom.BillingEngine billingEngine = (MercatorUi.Engine.Gescom.BillingEngine)sender;
            if (!string.IsNullOrEmpty(billingEngine.PiedsVRecord.PIECE_LIEE))
            {
                string reqSql = @"
                    select '<Files\'+rtrim(t.journal)+'\'+t.id+'\'+files.filename as filefullname
                        from pieds_v
                        cross apply dbo.DOC_LIES2(pieds_v.doc_lies) t
                        inner join FILES on files.filepath='<Files\'+t.journal+'\'+t.id+'\'
                        where (pieds_v.id=@id) and (pieds_v.journal=@journal) and (pieds_v.piece=@piece) and (files.filename is not null) ".UnIndent(5);
                List<string> l = Api.Zselect<string>(MercatorUi.Globals.RepData, reqSql, new MercatorSqlParam("@id", billingEngine.PiedsVRecord.ID, SqlDbType.Char), new MercatorSqlParam("@journal", billingEngine.PiedsVRecord.JOURNAL, SqlDbType.Char), new MercatorSqlParam("@piece", billingEngine.PiedsVRecord.PIECE));
                if (l != null)
                    e.Attachments.AddRange(l);
            }
        }
    }
}