using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Data.SqlClient;
using System.Reflection;

namespace XMLExtractor
{
    public class Image {
        public string id { get; set; }
        public string posizione { get; set; }
        public string descrizione { get; set; }
        public string byteImage { get; set; }
        public int idCapitolo { get; set; }
        public int idSezione { get; set; }
        public int idOrdinamento { get; set; }
        public int idPagina { get; set; }
        //public List<Nota> note { get; set; }

        public static List<string> getProperties()
        {
            List<string> properties = new List<string>();
            Image objectChart = new Image();
            foreach (var prop in objectChart.GetType().GetProperties())
            {
                properties.Add(prop.Name.ToLower());
            }

            properties.Remove("idcapitolo");
            properties.Remove("idsezione");
            properties.Remove("idordinamento");
            properties.Remove("idpagina");
            //properties.Remove("note");
            return properties;
        }

        public void writeDB(SqlConnection conn) {
            SqlCommand cmdCount = new SqlCommand("SELECT count(*) from REP_IMM_MON_IMAGE WHERE idRep_IMM_MON_Pagina = @idRep_IMM_MON_Pagina "
                +   "AND bytesImage = @bytesImage", conn);
            cmdCount.Parameters.AddWithValue("@idRep_IMM_MON_Pagina", this.idPagina);
            cmdCount.Parameters.AddWithValue("@bytesImage", this.byteImage);

            int idREP_IMM_MON_Template = Convert.ToInt32(cmdCount.ExecuteScalar());
            if (idREP_IMM_MON_Template == 0)
            {
                string sqlCommand = "(idREP_IMM_MON_Image, idREP_IMM_MON_Pagina, bytesImage, isIcon, descrizione, posizione) VALUES "
                    + "(@idREP_IMM_MON_Image, @idREP_IMM_MON_Pagina, @bytesImage, @isIcon, @descrizione, @posizione)";
                SqlCommand insertTo = new SqlCommand("INSERT INTO REP_IMM_MON_Image " + sqlCommand, conn);
                int primaryKey = Convert.ToInt32((new SqlCommand("SELECT count(*) from REP_IMM_MON_IMAGE", conn)).ExecuteScalar()) + 1;
                insertTo.Parameters.AddWithValue("@idREP_IMM_MON_Image", primaryKey);
                insertTo.Parameters.AddWithValue("@idREP_IMM_MON_Pagina", this.idPagina);
                insertTo.Parameters.AddWithValue("@bytesImage", this.id);
                insertTo.Parameters.AddWithValue("@isIcon", getIsIcon(this.posizione));
                insertTo.Parameters.AddWithValue("@descrizione", this.descrizione != null? this.descrizione : "");
                insertTo.Parameters.AddWithValue("@posizione", this.posizione.Substring(0,1));

                int rowsUpdatedInserted = insertTo.ExecuteNonQuery();
            }
        }

        public static void writeImage(XmlNode attribute, List<string> tagList, string nextTag, Data data)
        {
            Image image = new Image();
            //bool presenzaNota = attribute.ChildNodes.Cast<XmlNode>().Any(x => x.Name.Equals("note"));
            List<string> imageAttributes = Image.getProperties();
            //if (presenzaNota)
                //imageAttributes.Add("note");
            foreach (XmlNode attr in attribute.ChildNodes)
                if (!tagList.Contains(attr.Name.ToString()))
                {
                    PropertyInfo propertyInfo = image.GetType().GetProperty(attr.Name);
                    propertyInfo.SetValue(image, Convert.ChangeType(attr.InnerText, propertyInfo.PropertyType), null);
                    if (attr.Name.Contains("byteImage") && !attr.InnerText.Equals(""))
                        LoadImage(attr.InnerText, image.id);
                }
            image.idCapitolo = ReadXML.idCapitolo;
            image.idSezione = ReadXML.idSezione;
            image.idOrdinamento = ReadXML.idOrdinamento;
            image.idPagina = ReadXML.idPagina;
            data.imageList.Add(image);
            ReadXML.idOrdinamento++;
            imageAttributes = Image.getProperties();

        }

        public static void writeIcon(XmlNodeList node, Data data)
        {

            List<string> attributes = new List<string>() { "name", "position" };
            foreach (XmlNode tag in node)
            {
                Image image = new Image();
                foreach (XmlNode innerTag in tag.ChildNodes)
                {
                    string attributeName = innerTag.Name.Equals("name") ? "id" : 
                        (innerTag.Name.Equals("position") ? "posizione" : innerTag.Name);
                    PropertyInfo propertyInfo = image.GetType().GetProperty(attributeName);
                    propertyInfo.SetValue(image, Convert.ChangeType(
                        attributeName.Equals("id") ? innerTag.InnerText+".jpeg": innerTag.InnerText, propertyInfo.PropertyType), null);
                }

                image.byteImage = image.id;
                image.idCapitolo = ReadXML.idCapitolo;
                image.idSezione = ReadXML.idSezione;
                image.idOrdinamento = ReadXML.idOrdinamento; ;
                image.idPagina = ReadXML.idPagina;
                
                data.imageList.Add(image);
                ReadXML.idOrdinamento++;
            }
        }

        public static int getIsIcon (string position) {

            Dictionary<string, int> isIcon = new Dictionary<string, int>();
            isIcon.Add("L", 0);
            isIcon.Add("R", 0);
            isIcon.Add("A", 0);
            isIcon.Add("LB", 3);
            isIcon.Add("RB", 4);
            isIcon.Add("LT", 1);
            isIcon.Add("RT", 2);

            return isIcon[position];
        }

        public static void LoadImage(string byteImage, string nameImage)
        {
            // Convert Base64 String to byte[]
            byte[] imageBytes = Convert.FromBase64String(byteImage);
            MemoryStream ms = new MemoryStream(imageBytes, 0,
              imageBytes.Length);

            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            System.Drawing.Image image = System.Drawing.Image.FromStream(ms, false, true);
            image.Save(@"C:\Users\nazio\Desktop\Immobiliare Monitoraggio\" + nameImage+".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);     
        }
    }
}
