using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace digioz
{

    public class NonRelationalHelper
    {
        private string csInsertsFile = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\inserts.txt";
        private StringBuilder csInstallationMessage = new StringBuilder();

        public string InsertsFilePath
        {
            get { return csInsertsFile; }
            set { csInsertsFile = value; }
        }

        public string InstallationMessage
        {
            get { return csInstallationMessage.ToString(); }            
        }

        private object GetValue(string psString, Type poType)
        {
            psString = psString.Replace("\"", "").Trim();
            if (poType == typeof(string))
            {
                return psString;
            }
            else
            {
                if (string.IsNullOrEmpty(psString))
                {
                    return null;
                }
                else
                {
                    return System.Convert.ChangeType(psString, poType);
                }
            }            
        }

        public NonRelationalHelper() { }

        public int Install()
        {
            int liCount = 0;
            // Get the content of the data file.
            FileStream lsStream = new FileStream(csInsertsFile, FileMode.Open, FileAccess.Read);
            StreamReader lsReader = new StreamReader(lsStream);
            //digioz.XML loXML = new digioz.XML(PortalSettingsManagement.GetPortalSettings());
            digioz.IDataNonRelational lodb = DataFactoryNonRelational.GetDataObject(PortalSettingsManagement.GetPortalSettings());
            lodb.openEntity();
            string lsLine;            
            object loObj;
            string lsType;
            string[] lsParameters;
            // Clean message
            csInstallationMessage.Length = 0;
            csInstallationMessage.AppendLine("Installing entities into XML storage...");
            try
            {                
                while ((lsLine = lsReader.ReadLine()) != null)
                {
                    if (lsLine != "" && !lsLine.Trim().StartsWith(@"//"))
                    {
                        lsType = lsLine.Substring(0, lsLine.IndexOf("{")).Trim();
                        lsParameters = lsLine.Substring(lsLine.IndexOf("{") + 1, lsLine.IndexOf("}") - lsLine.IndexOf("{") - 1).Split(',');

                        // Instantiate the object.
                        // object loObj = Activator.CreateInstance(Type.GetType(m.GetType().FullName));                
                        loObj = Type.GetType(lsType).InvokeMember(null, BindingFlags.CreateInstance, null, null, null);
                        for (int i = 0; i < lsParameters.Length; i = i + 2)
                        {
                            object[] loArg = new object[] { this.GetValue(lsParameters[i + 1], Type.GetType(lsType).GetProperty(lsParameters[i].Trim()).PropertyType) };
                            Type.GetType(lsType).InvokeMember(lsParameters[i].Trim(), BindingFlags.SetProperty, null, loObj, loArg);
                        }
                        // Save the object.                        
                        lodb.SaveEntity(loObj);
                        csInstallationMessage.AppendLine(lsType + " entity has been saved.");
                        liCount++;
                    }
                }
            }            
            finally
            {
                lsReader.Close();
                lsStream.Close();
                lodb.closeEntity();
            }
            csInstallationMessage.AppendLine("Finished installation. " + liCount.ToString() + " entities has been saved into XML.");
            return liCount;
        }

        public static void RemoveExistingXML()
        {
            string[] lsFiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "App_Data", "*_*.xml");
            for (int i = 0; i < lsFiles.Length; i++)
            {
                File.Delete(lsFiles[i]);
            }
        }
        /*
        public void ProcessFile()
        {
            int liCount = 0;
            StringBuilder sb = new StringBuilder();
           
            // Get the content of the data file.
            FileStream lsStream = new FileStream(csInsertsFile, FileMode.Open, FileAccess.Read);
            StreamReader lsReader = new StreamReader(lsStream);
            string lsLine;
            while ((lsLine = lsReader.ReadLine()) != null)
            {
                if (lsLine != "")
                {
                    string lsType = lsLine.Substring(0, lsLine.IndexOf("{")).Trim();
                    string[] lsParameters = lsLine.Substring(lsLine.IndexOf("{") + 1, lsLine.IndexOf("}") - lsLine.IndexOf("{") - 1).Split(',');

                    switch (lsType)
                    {
                        case "MenuItem":
                            sb.AppendLine(lsType + "{" + "Name, " + lsParameters[0] + ", ActionType," + lsParameters[1] + ", ActionData, " + lsParameters[2] + ", BoxID, " + lsParameters[3] + "}");
                            break;
                        case "BoxItem":
                            //BoxItem{ 'Poll','L',2,'X','controls/poll/Poll.ascx'}
                            sb.AppendLine(lsType + "{" + "Name, " + lsParameters[0] + ", Location," + lsParameters[1] + ", Order, " + lsParameters[2] + ", ActionType, " + lsParameters[3] + ", ActionData, " + lsParameters[4] + "}");
                            break;
                        case "AdminMenuItem":
                            sb.AppendLine(lsType + "{" + "Name, " + lsParameters[0] + ", Data, " + lsParameters[1] + "}");
                            break;
                        case "Configuration":
                            sb.AppendLine(lsType + "{" + "KeyName, " + lsParameters[0] + ", KeyValue, " + lsParameters[1] + ", Removable, " + lsParameters[2] + "}");
                            break;
                        case "Extension":
                            sb.AppendLine(lsType + "{" + "Name, " + lsParameters[0] + ", Value, " + lsParameters[1] + ", Allowed, " + lsParameters[2] + "}");
                            break;
                        case "PollOptionInfo":
                            sb.AppendLine(lsType + "{" + "SubjectID, " + lsParameters[0] + ", OptionName, " + lsParameters[1] + "}");
                            break;
                        case "UserPermission":
                            sb.AppendLine(lsType + "{" + "Value, " + lsParameters[0] + ", Description, " + lsParameters[1] + "}");
                            break;
                        default:
                            sb.AppendLine(lsLine);
                            break;
                    }
                    
                    // Save the object.
                    liCount++;
                }
            }
            lsReader.Close();
            lsStream.Close();
            
            File.AppendAllText(csInsertsFile+".txt",sb.ToString());
        }
        */
    }
}
