using System;
using System.Linq;
using DevExpress.ExpressApp;
using System.Collections.Generic;
using DevExpress.ExpressApp.Actions;
using DevExpress.Persistent.Validation;
using System.Xml;
using DevExpress.Xpo;
using DevExpress.ExpressApp.Xpo;
using DevExpress.Data.Filtering;
using Nuvolar.Module;
using System.Globalization;
using System.Windows.Forms;
namespace Nuvolar.Module
{
    // For more typical usage scenarios, be sure to check out http://documentation.devexpress.com/#Xaf/clsDevExpressExpressAppViewControllertopic.
    public partial class NavInvoiceReportVC : ViewController
    {
        public NavInvoiceReportVC()
        {
            InitializeComponent();
            RegisterActions(components);
            // Target required Views (via the TargetXXX properties) and create their Actions.
        }
        protected override void OnActivated()
        {
            base.OnActivated();
            // Perform various tasks depending on the target View.
        }
        protected override void OnViewControlsCreated()
        {
            base.OnViewControlsCreated();
            // Access and customize the target View control.
        }
        protected override void OnDeactivated()
        {
            // Unsubscribe from previously subscribed events and release other references and resources.
            base.OnDeactivated();
        }

        private void aCreateNAVInvoiceReportXML_Execute(object sender, SimpleActionExecuteEventArgs e)
        {

            XPObjectSpace _ocur = (XPObjectSpace)View.ObjectSpace;
            XPObjectSpace _onew = (XPObjectSpace)Application.CreateObjectSpace();
            NAVInvoiceReport _NAVInvoiceReport = (NAVInvoiceReport)View.SelectedObjects[0];

            //Kritéria a törzsből
            System.String _Criteria=" IsEditable=false and IsProforma=false and DocumentNumber!='' and IsNull(DocumentNumber)=false";
            
            if (string.IsNullOrEmpty(_NAVInvoiceReport.DocumentNumberFrom)==false & string.IsNullOrEmpty(_NAVInvoiceReport.DocumentNumberTo)==false)
            {
                _Criteria += string.Format(" and (DocumentNumber>='{0}' and DocumentNumber <='{1}')", _NAVInvoiceReport.DocumentNumberFrom, _NAVInvoiceReport.DocumentNumberTo);
            }
            _Criteria += " and (GetDate(DateCreated)>=? and GetDate(DateCreated)<=?)";
            XPCollection<InvoiceHeader> _InvoiceHeader_Collection = new XPCollection<InvoiceHeader>(_onew.Session, CriteriaOperator.Parse(_Criteria, _NAVInvoiceReport.FromDate, _NAVInvoiceReport.ToDate));
            
            _InvoiceHeader_Collection.Sorting.Add(new SortProperty("DateCreated", DevExpress.Xpo.DB.SortingDirection.Ascending));

            System.String _Filename = string.Format(@"NR{0:yyyyMMddHHmm}.xml", System.DateTime.Now);
            if (Validator.RuleSet.ValidateAll(View.ObjectSpace, View.SelectedObjects, DefaultContexts.Save))
            {

                XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, NewLineOnAttributes = true };
                using (XmlWriter writer = XmlWriter.Create(string.Format(@"{0}\{1}",_NAVInvoiceReport.OutputPath,_Filename), settings))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("szamlak", @"http://schemas.nav.gov.hu/2013/szamla");
                    writer.WriteElementString("export_datuma", DateTime.Now.ToString(@"yyyy-MM-dd"));
                    writer.WriteElementString("export_szla_db", _InvoiceHeader_Collection.Count.ToString());
                    writer.WriteElementString("kezdo_ido", _NAVInvoiceReport.FromDate.ToString(@"yyyy-MM-dd"));
                    writer.WriteElementString("zaro_ido", _NAVInvoiceReport.ToDate.ToString(@"yyyy-MM-dd"));
                    writer.WriteElementString("kezdo_szamlaszam", _NAVInvoiceReport.DocumentNumberFrom);
                    writer.WriteElementString("zaro_szamlaszam", _NAVInvoiceReport.DocumentNumberTo);

                    foreach (InvoiceHeader _InvoiceHeader in _InvoiceHeader_Collection)
                    {
                        writer.WriteStartElement("szamla");

                        writer.WriteStartElement("fejlec");
                        writer.WriteElementString("szlasorszam", _InvoiceHeader.DocumentNumber);
                        writer.WriteElementString("szlatipus", "1");
                        writer.WriteElementString("szladatum", _InvoiceHeader.DateCreated.ToString(@"yyyy-MM-dd"));
                        writer.WriteElementString("teljdatum", _InvoiceHeader.DateExecution.ToString(@"yyyy-MM-dd"));

                        writer.WriteEndElement();//fejlec

                        writer.WriteStartElement("szamlakibocsato");
                        writer.WriteElementString("adoszam", _InvoiceHeader.Saved_CustomersFrom_VATNumber);
                        writer.WriteElementString("kisadozo", "false");
                        writer.WriteElementString("nev", _InvoiceHeader.Saved_CustomersFrom_Name);

                        writer.WriteStartElement("cim");
                        writer.WriteElementString("iranyitoszam", _InvoiceHeader.Saved_CustomersFrom_Address_ZipPostal);
                        writer.WriteElementString("telepules", _InvoiceHeader.Saved_CustomersFrom_Address_City);

                        if (_InvoiceHeader.CustomersFrom.Address1.GetMemberValue("NameOfStreet") != null)
                        { writer.WriteElementString("kozterulet_neve", _InvoiceHeader.CustomersFrom.Address1.GetMemberValue("NameOfStreet").ToString()); } 
                        else 
                        { writer.WriteElementString("kozterulet_neve", _InvoiceHeader.Saved_CustomersFrom_Address_Street); }
                        

                        if (_InvoiceHeader.CustomersFrom.Address1.GetMemberValue("District") != null) { writer.WriteElementString("kerulet", _InvoiceHeader.CustomersFrom.Address1.GetMemberValue("District").ToString()); }
                        if (_InvoiceHeader.CustomersFrom.Address1.GetMemberValue("TypeOfStreet") != null) { writer.WriteElementString("kozterulet_jellege", _InvoiceHeader.CustomersFrom.Address1.GetMemberValue("TypeOfStreet").ToString()); }
                        if (_InvoiceHeader.CustomersFrom.Address1.GetMemberValue("NumberOfStreet") != null) { writer.WriteElementString("hazszam", _InvoiceHeader.CustomersFrom.Address1.GetMemberValue("NumberOfStreet").ToString()); }
                        if (_InvoiceHeader.CustomersFrom.Address1.GetMemberValue("Building") != null) { writer.WriteElementString("epulet", _InvoiceHeader.CustomersFrom.Address1.GetMemberValue("Building").ToString()); }
                        if (_InvoiceHeader.CustomersFrom.Address1.GetMemberValue("StairCase") != null) { writer.WriteElementString("lepcsohaz", _InvoiceHeader.CustomersFrom.Address1.GetMemberValue("StairCase").ToString()); }
                        if (_InvoiceHeader.CustomersFrom.Address1.GetMemberValue("Floor") != null) { writer.WriteElementString("szint", _InvoiceHeader.CustomersFrom.Address1.GetMemberValue("Floor").ToString()); }
                        if (_InvoiceHeader.CustomersFrom.Address1.GetMemberValue("NumberOfDoor") != null) { writer.WriteElementString("ajto", _InvoiceHeader.CustomersFrom.Address1.GetMemberValue("NumberOfDoor").ToString()); }

                        //writer.WriteElementString("kerulet", (_InvoiceHeader.CustomersFrom.Address1.GetMemberValue("District") ?? "").ToString()); 
                        
                        writer.WriteElementString("egyeni_vallalkozo", "");
                        writer.WriteElementString("ev_nyilv_tart_szam", "");
                        writer.WriteElementString("ev_neve", "");
                        writer.WriteEndElement();//cim

                        writer.WriteEndElement();//szamlakibocsato

                        writer.WriteStartElement("vevo");
                        writer.WriteElementString("nev", _InvoiceHeader.Saved_Customers_Name);

                        writer.WriteStartElement("cim");
                        writer.WriteElementString("iranyitoszam", _InvoiceHeader.Saved_Customers_Address_ZipPostal);
                        writer.WriteElementString("telepules", _InvoiceHeader.Saved_Customers_Address_City);
                        if (_InvoiceHeader.Customers.Address1.GetMemberValue("NameOfStreet") != null)
                        { writer.WriteElementString("kozterulet_neve", _InvoiceHeader.Customers.Address1.GetMemberValue("NameOfStreet").ToString()); }
                        else
                        { writer.WriteElementString("kozterulet_neve", _InvoiceHeader.Saved_Customers_Address_Street); }
                        

                        if (_InvoiceHeader.Customers.Address1.GetMemberValue("District") != null) { writer.WriteElementString("kerulet", _InvoiceHeader.Customers.Address1.GetMemberValue("District").ToString()); }
                        if (_InvoiceHeader.Customers.Address1.GetMemberValue("TypeOfStreet") != null) { writer.WriteElementString("kozterulet_jellege", _InvoiceHeader.Customers.Address1.GetMemberValue("TypeOfStreet").ToString()); }
                        if (_InvoiceHeader.Customers.Address1.GetMemberValue("NumberOfStreet") != null) { writer.WriteElementString("hazszam", _InvoiceHeader.Customers.Address1.GetMemberValue("NumberOfStreet").ToString()); }
                        if (_InvoiceHeader.Customers.Address1.GetMemberValue("Building") != null) { writer.WriteElementString("epulet", _InvoiceHeader.Customers.Address1.GetMemberValue("Building").ToString()); }
                        if (_InvoiceHeader.Customers.Address1.GetMemberValue("StairCase") != null) { writer.WriteElementString("lepcsohaz", _InvoiceHeader.Customers.Address1.GetMemberValue("StairCase").ToString()); }
                        if (_InvoiceHeader.Customers.Address1.GetMemberValue("Floor") != null) { writer.WriteElementString("szint", _InvoiceHeader.Customers.Address1.GetMemberValue("Floor").ToString()); }
                        if (_InvoiceHeader.Customers.Address1.GetMemberValue("NumberOfDoor") != null) { writer.WriteElementString("ajto", _InvoiceHeader.Customers.Address1.GetMemberValue("NumberOfDoor").ToString()); }
                        
                        writer.WriteEndElement();//cim

                        writer.WriteEndElement();//vevo
                        foreach (InvoiceRows _InvoiceRows in _InvoiceHeader.InvoiceRows)
                        {
                            writer.WriteStartElement("termek_szolgaltatas_tetelek");
                            writer.WriteElementString("termeknev", _InvoiceRows.ShortName);
                            writer.WriteElementString("menny", _InvoiceRows.QTT.ToString("F", CultureInfo.InvariantCulture));
                            writer.WriteElementString("mertekegys", _InvoiceRows.Units.ShortName);
                            writer.WriteElementString("nettoar", _InvoiceRows.SumPriceHUF.ToString("F", CultureInfo.InvariantCulture));
                            writer.WriteElementString("nettoegysar", _InvoiceRows.ListPriceHUF.ToString("F", CultureInfo.InvariantCulture));
                            writer.WriteElementString("adokulcs", _InvoiceRows.VAT.KeyValue.ToString("F", CultureInfo.InvariantCulture));
                            writer.WriteElementString("adoertek", (_InvoiceRows.SumPriceBruttoHUF - _InvoiceRows.SumPriceHUF).ToString("F", CultureInfo.InvariantCulture));
                            writer.WriteElementString("bruttoar", _InvoiceRows.SumPriceBruttoHUF.ToString("F", CultureInfo.InvariantCulture));

                            writer.WriteEndElement();//termek_szolgaltatas_tetelek
                        }

                        writer.WriteStartElement("zaradekok");
                        writer.WriteElementString("adoment_hiv", "false");
                        writer.WriteEndElement(); //zaradekok

                        writer.WriteStartElement("nem_kotelezo");
                        writer.WriteElementString("fiz_hatarido", _InvoiceHeader.DatePayment.ToString(@"yyyy-MM-dd"));
                        writer.WriteElementString("fiz_mod", _InvoiceHeader.PaymentOption.ShortName);
                        writer.WriteElementString("penznem", _InvoiceHeader.CurrencyName.ShortName);
                        writer.WriteEndElement(); //nem_kotelezo

                        writer.WriteStartElement("osszesites");
                        foreach (InvoiceVATRows _InvoiceVATRows in _InvoiceHeader.InvoiceVATRows)
                        {
                            writer.WriteStartElement("afarovat");
                            writer.WriteElementString("nettoar", _InvoiceVATRows.AmountNettoHUF.ToString("F", CultureInfo.InvariantCulture));
                            writer.WriteElementString("adokulcs", _InvoiceVATRows.VAT.KeyValue.ToString("F", CultureInfo.InvariantCulture));
                            writer.WriteElementString("adoertek", _InvoiceVATRows.AmountVATHUF.ToString("F", CultureInfo.InvariantCulture));
                            writer.WriteElementString("bruttoar", _InvoiceVATRows.AmountBruttoHUF.ToString("F", CultureInfo.InvariantCulture));

                            writer.WriteEndElement(); //afarovat
                        }
                        writer.WriteStartElement("vegosszeg");
                        writer.WriteElementString("nettoarossz", _InvoiceHeader.TotalNettoHUF.ToString("F", CultureInfo.InvariantCulture));
                        writer.WriteElementString("afaertekossz", _InvoiceHeader.TotalVATHUF.ToString("F", CultureInfo.InvariantCulture));
                        writer.WriteElementString("bruttoarossz", _InvoiceHeader.TotalBruttoHUF.ToString("F", CultureInfo.InvariantCulture));

                        writer.WriteEndElement(); //vegosszeg
                        writer.WriteEndElement(); //osszesites

                        writer.WriteEndElement(); //szamla
                    }

                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                    MessageBox.Show(string.Format("A letöltés befejeződött !\nA fájl a következő helyen :\n{0}", string.Format(@"{0}\{1}", _NAVInvoiceReport.OutputPath, _Filename)), "Adatletöltés állapota", MessageBoxButtons.OK); 
                }
            }
        }

        private void simpleAction1_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            DevExpress.ExpressApp.Reports.Win.ReportsController _ReportsController = Frame.GetController<DevExpress.ExpressApp.Reports.Win.ReportsController>();
            
            _ReportsController.ShowReportDesignerAction.DoExecute();
        }
    }
}
