﻿using Bivi.Infrastructure.Services.Imports;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace Bivi.Infrastructure.Services.Implementations.Imports
{
    public class ExcelImport : IExcelImport
    {
        public string PreProcessFile(string fileContent)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(fileContent);

            //Instantiate an XmlNamespaceManager object. 
            var xmlnsManager = new System.Xml.XmlNamespaceManager(xmlDoc.NameTable);

            //Add the namespaces used in books.xml to the XmlNamespaceManager.
            xmlnsManager.AddNamespace("", "urn:schemas-microsoft-com:office:excel");
            xmlnsManager.AddNamespace("o", "urn:schemas-microsoft-com:office:office");
            xmlnsManager.AddNamespace("x", "urn:schemas-microsoft-com:office:excel");
            xmlnsManager.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");
            xmlnsManager.AddNamespace("html", "http://www.w3.org/TR/REC-html40");

            foreach (XmlNode node in xmlDoc.SelectNodes("//ss:Row", xmlnsManager))
            {
                var index = 1;
                foreach (XmlNode cellNode in node.SelectNodes("./ss:Cell", xmlnsManager))
                {
                    var indexAttr = cellNode.Attributes.GetNamedItem("ss:Index");
                    if (indexAttr != null)
                    {
                        index = Convert.ToInt32(indexAttr.Value) + 1;
                    }
                    else
                    {
                        var cellAttr = xmlDoc.CreateAttribute("ss", "Index", "urn:schemas-microsoft-com:office:spreadsheet");
                        cellAttr.Value = index.ToString();
                        cellNode.Attributes.Append(cellAttr);
                        index++;
                    }
                }
            }

            return xmlDoc.OuterXml;
        }
    }
}
