using System;
using System.Collections.Generic;
using System.Linq;
using Consulenza.ExternalServices;
using Consulenza.ReportWriter.Business;
using Consulenza.ReportWriter.Business.OBJ_PDF;
using System.Data;
using Consulenza.ReportWriter.Business.CHART_PDF;
using Consulenza.ReportCommon;
using Consulenza.ReportWriter.Business.Entity;
using System.Text;
using System.IO;
using System.Drawing.Imaging;
using System.Globalization;

namespace Consulenza.ReportWriter.Manager.Section.Immobiliare.Monitoraggio
{
    /// <summary>
    /// Scheda 28 - Distribuzione Geografica - Estero
    /// </summary>
    public class S28 : Entity.Section
    {
        public string sImagePosition = "";

        public S28(EnvironmentFacade environmentFacade, int idSection)
            : base(environmentFacade, idSection)
        {
            try
            {
                Draw();
            }
            catch (Exception ex)
            {
                SectionLogger.Write("S28", ex.Message, SectionLoggerMessageLevel.E, EnvironmentFacade.ReportEnvironment);
            }
        }

        /// <summary>
        /// Scheda28. Patrimonio immobiliare – Estero 
        /// </summary>
        protected override sealed void Draw()
        {
            var ds = GetDataSet();

            var image = getImageFromStored();
            AddElement(new FormattedTextAreaPDF("Di seguito si rappresenta la distribuzione geografica degli immobili ubicati all'Estero.", 30)
            {
                AutoIncrementYWritable = false,                
                Width = 800,
                FontSize = 9.96f,
                FontColor = new ColorPDF(91, 88, 79),
                Y = 60
            });

            #region TO DELETE
            //// Image EUROPA - PROMETEIA
            //AddElement(new ImagePDF(455, 0.25f, image)            
            //{
            //    AutoIncrementYWritable = false,
            //    Y = 80
            //});
            //// Image WORLD - PROMETEIA
            //AddElement(new ImagePDF(430, 0.25f, image)
            //{
            //    AutoIncrementYWritable = false,
            //    Y = 80
            //});

            //// Image EUROPA - MINE
            //AddElement(new ImagePDF(330, 0.58f, image)            
            //{
            //    AutoIncrementYWritable = false,
            //    Y = 70
            //});
            //// Image WORLD - MINE
            //AddElement(new ImagePDF(80, 0.63f, image)
            //{
            //    AutoIncrementYWritable = false,
            //    Y = 75
            //});
            //AddElement(new SpacePDF(280));
            #endregion


            int deltaY = 0;
            switch (ds.Tables["sintesi"].Rows.Count)
            {
                case 1:
                    deltaY = 0;
                    break;
                case 2:
                    deltaY = 17;
                    break;
                case 3:
                    deltaY = 34;
                    break;
                case 4:
                    deltaY = 51;
                    break;
                case 5:
                    deltaY = 68;
                    break;
                case 6:
                    deltaY = 85;
                    break;
                case 7:
                    deltaY = 102;
                    break;
                default:
                    deltaY = 119;
                    break;
            }

            // Image WORLD - NEW PROMETEIA
            //var imagePatch1 = new ImagePDF(655, 0.20F, "BlankPatch.png") { Y = 440, AutoIncrementYWritable = false };
            //AddElement(imagePatch1);
            //var imagePatch2 = new ImagePDF(655, 0.20F, "BlankPatch.png") { Y = 460, AutoIncrementYWritable = false };
            //AddElement(imagePatch2);
            if (sImagePosition == "C")
            { 
                AddElement(new ImagePDF(80, 0.56f, image)
                {
                    AutoIncrementYWritable = false,
                    Y = 75
                });
                //AddElement(new SpacePDF(310));
                AddElement(new SpacePDF(368 - deltaY));
            }
            else
            {
                AddElement(new ImagePDF(220, 0.6273f, image)
                {
                    AutoIncrementYWritable = false,
                    Y = 80
                });
                AddElement(new SpacePDF(368 - deltaY));
            }
            //// Image EUROPE - NEW PROMETEIA
            ////var imagePatch = new ImagePDF(655, 0.19F, "BlankPatch.png" ) { Y = 460, AutoIncrementYWritable = false };
            ////AddElement(imagePatch);
            //AddElement(new ImagePDF(220, 0.6273f, image)
            //{
            //    AutoIncrementYWritable = false,
            //    Y = 80                
            //});
            //AddElement(new SpacePDF(368 - deltaY));


            // Disegnare Tabella
            var table = new TablePDF(20, ds.Tables["sintesi"], ds.Tables["sintesiTotale"])
            {
                Style = Style.Immobiliare,
                AlternateRow = false,
                HeaderHeight = 12,
                RowHeight = 10,
                FooterHeight = 13,
                //AdditionalSpaceBetweenHeadersAndTable = 5.0F,
                HeaderTextVerticalAlign = VerticalAlignmentType.Basso,
                AutoIncrementYWritable = false,
                ShowBorderLastLine = false,
                ShowBorderLastLineInPageBreak = false,
                ShowBorderHeader = false
            };
            table.Columns.Add(new ColumnPDF("codStato", 25, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Immagine, "codStato", "") { HeaderFontSize = 7, ScaleColumnTypeImage = 0.3F, VerticalAlignment = VerticalAlignmentType.Basso });
            table.Columns.Add(new ColumnPDF("comune", 90, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Testo, "comune", "Nazione") { HeaderFontSize = 7, VerticalAlignment = VerticalAlignmentType.Basso });
            table.Columns.Add(new ColumnPDF("numero", 25, HorizontalAlignmentType.Centrato, false, false, 7, ColumnType.Testo, "numero", "")
            {  
                HeaderGroupWidth = 25,
                HeaderGroupPathImage ="CASANERA.png",
                HeaderGroupScaleImage = 0.07F,
                HeaderGroupTextDeltaX = 5,
                HeaderGroupBorderLine = false,
                VerticalAlignment = VerticalAlignmentType.Basso
             });

            table.Columns.Add(new ColumnPDF("totale", 75,HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Testo, "totaleCurrency", "") 
            {  
                HeaderGroupWidth = 75,
                HeaderGroupPathImage ="Euro.png",
                HeaderGroupScaleImage = 0.07F,
                HeaderGroupTextDeltaX = 45,   
                HeaderGroupBorderLine = false,
                VerticalAlignment = VerticalAlignmentType.Basso,
             });

            table.FooterColumns.Add(new ColumnPDF("spazio", 25, HorizontalAlignmentType.Sinistra, false, true, 7, ColumnType.Testo));
            table.FooterColumns.Add(new ColumnPDF("comuneTotale", 90, HorizontalAlignmentType.Sinistra, false, true, 7, ColumnType.Testo));
            table.FooterColumns.Add(new ColumnPDF("numeroTotale", 25, HorizontalAlignmentType.Centrato, false, true, 7, ColumnType.Testo));
            table.FooterColumns.Add(new ColumnPDF("totaleTotale", 75, HorizontalAlignmentType.Destra, false, true, 7, ColumnType.Testo));

            //float startFrameX = table.X + table.Width + 10;
            //float startFrameY = 94;
            //addFrame(startFrameX, startFrameX + 320, startFrameY, startFrameY + 350);

            AddElement(table);

        }

        /// <summary>
        /// Recupera i dati necessari alla Section restituendo un DataTable.
        /// </summary>
        /// <returns></returns>
        protected override DataTable GetDataTable()
        {
            return null;
        }

        /// <summary>
        /// Recupera i dati necessari alla Section restituendo un DataSet.
        /// </summary>
        /// <returns></returns>
        protected override DataSet GetDataSet()
        {
            #region Definizione dei parametri

            var parametri = new List<Parametro>
            {
                new Parametro
                {
                    Direction = ParameterDirection.Input,
                    DbType = DbType.Int64,
                    ParameterName = "ChiaveClientePB",
                    Value = EnvironmentFacade.ReportEnvironment.Cliente.Chiave
                }
            };

            #endregion


            var dt = DataAccess.ExecuteDataSetStoredProcedure(DBProvider.SqlServerConsulenzaUnica, "REP_ImmobiliareMonitoraggio_S28_MapStratImmEstero", parametri);

            //DataTable table = new DataTable();
            //table.Columns.Add("comune", typeof(string));
            //table.Columns.Add("numero", typeof(string));
            //table.Columns.Add("totale", typeof(string));
            //table.Columns.Add("ImmagineBandiera", typeof(byte));

            DataTable tableTotale = new DataTable();
            tableTotale.Columns.Add("spazio", typeof(string));
            tableTotale.Columns.Add("comuneTotale", typeof(string));
            tableTotale.Columns.Add("numeroTotale", typeof(string));
            tableTotale.Columns.Add("totaleTotale", typeof(string));

            int nTotImmobili = 0;
            decimal nTotValore = 0;

            //DataTable table = dt.Tables[0].Copy();
            DataTable table = dt.Tables[0].AsEnumerable().OrderByDescending(o => o.Field<decimal>("totale")).CopyToDataTable();
            
            table.Columns.Add("totaleCurrency", typeof(string));
            for (int i = 0; i < dt.Tables[0].Rows.Count; i++)            
            {
                nTotImmobili = nTotImmobili + Convert.ToInt16(table.Rows[i]["numero"]);
                nTotValore= nTotValore + Convert.ToDecimal(table.Rows[i]["totale"]);

                //table.Rows[i]["comune"] = Helper.CapitalizeWords(table.Rows[i]["comune"].ToString().ToLower());               
                table.Rows[i]["totaleCurrency"] = Helper.FormatCurrency(table.Rows[i]["totale"].ToString());
                table.Rows[i]["codStato"] = "Flags\\" + table.Rows[i]["codStato"].ToString() + ".png";
            }
            
            tableTotale.Rows.Add(" ","Totale", nTotImmobili, Helper.FormatCurrency(nTotValore.ToString()));
                //rowTotale["numImmobiliTotale"],
                //Helper.FormatCurrency(rowTotale["valProQuotaTotale"].ToString()),
                //Helper.FormatCurrency(rowTotale["valTotaleTotale"].ToString()),
                //Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(rowTotale["pesoTotale"].ToString(), 4)) * 100, 1));

            DataSet ds = new DataSet();
            table.TableName = "sintesi";
            tableTotale.TableName = "sintesiTotale";
            ds.Tables.Add(table);
            ds.Tables.Add(tableTotale);

            return ds;

        }

        public virtual Stream getImageFromStored()
        {
            var parametri = new List<Parametro>
            {
                new Parametro
                {
                    Direction = ParameterDirection.Input,
                    DbType = DbType.Int32,
                    ParameterName = "chiaveClientePB",
                    Value = EnvironmentFacade.ReportEnvironment.Cliente.Chiave
                },
                new Parametro
                {
                    Direction = ParameterDirection.Input,
                    DbType = DbType.Int32,
                    ParameterName = "chiaveNucleo",
                    Value = 0
                }
            };

            var data = DataAccess.ExecuteDataSetStoredProcedure(DBProvider.SqlServerConsulenzaUnica, "REP_ImmobiliareMonitoraggio_S14_MapDistrGeografica_Image", parametri);


            byte[] imageBytes = (byte[])data.Tables[0].Rows[0][3];
            sImagePosition = data.Tables[0].Rows[0][4].ToString();

            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
            ms.Write(imageBytes, 0, imageBytes.Length);
            return ms;
        }

        public void addFrame(float XupSx, float XupDx, float Yup, float Ydown)
        {

            var horizontalTopLine = new LinePDF(XupSx, Yup, XupDx, Yup, 0.5F, ColorPDF.Immobiliare_Grigio_TitoloPiccolo) { AutoIncrementYWritable = false };
            AddElement(horizontalTopLine);
            var horizontalBottomLine = new LinePDF(XupSx, Ydown, XupDx, Ydown, 0.5F, ColorPDF.Immobiliare_Grigio_TitoloPiccolo) { AutoIncrementYWritable = false };
            AddElement(horizontalBottomLine);
            var verticalLeftLine = new LinePDF(XupSx, Yup, XupSx, Ydown, 0.5F, ColorPDF.Immobiliare_Grigio_TitoloPiccolo) { AutoIncrementYWritable = false };
            AddElement(verticalLeftLine);
            var verticalRightLine = new LinePDF(XupDx, Yup, XupDx, Ydown, 0.5F, ColorPDF.Immobiliare_Grigio_TitoloPiccolo) { AutoIncrementYWritable = false };
            AddElement(verticalRightLine);
        }

        public string getTipologia(string tipologia)
        {
            switch (tipologia)
            {
                case "U":
                    return "<B>Uso abitativo</B>";
                case "I":
                    return "<B>Investimento</B>";
                case "S":
                    return "<B>Strumentale</B>";
                case "NS":
                    return "<B>Non specificata</B>";
                default:
                    return "";
            }
        }

    }
}
