using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Yaulw.Assembly;

namespace Installables.All
{
    /// <summary>
    /// Responsible for working with setup components which don't require any special treatment
    /// </summary>
    public class Component_Setup_Manager : IDisposable, IManageComponents
    {
        #region Private Members

        private bool _disposed = false;

        private Dictionary<string, Assembly> _componentsLoaded = new Dictionary<string, Assembly>();

        #endregion

        #region Construction

        /// <summary>
        /// Constructor
        /// </summary>
        public Component_Setup_Manager()
        {            
        }

        /// <summary>
        /// Finalizer
        /// </summary>
        ~Component_Setup_Manager()
        {
            Dispose(true);
        }

        #endregion

        #region IManageComponents Members

        /// <summary>
        /// Checks if there are Newer Components embedded then that were installed on the system
        /// </summary>
        /// <returns>true, if newer components were found, false otherwise</returns>
        public bool AreNewerComponentsAvailable()
        {
            //# If nothing is installed, no need to continue            
            if (GetAllInstalledComponents() == null)
                return true;

            // if the lengths don't match, something must get installed
            if (GetAllInstalledComponents().Length != GetAllEmbeddedComponents().Length)
                return true;

            // # Otherwise, let's determine 1 by 1
            foreach (ComponentConfig.Component component in GetAllEmbeddedComponents())
            {
                int nIndex = Common.GetIndexForComponentUniqueLabel(component.UniqueLabel, GetAllInstalledComponents());
                if (nIndex == -1)
                    return true;
                else if (GetAllInstalledComponents()[nIndex].CompareTo(component) != 0)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// Returns the Component Definitions for all Newer components found on the system
        /// </summary>
        /// <returns>a list of newer setup components, or empty list for none</returns>
        public IInstallComponent[] GetNewerComponents(ref SetupEvents setupEventObj)
        {
            // # Extract all, or let's determine 1 by 1 and extract
            bool bInstalledCompsFound = (GetAllInstalledComponents() != null);
            foreach (ComponentConfig.Component component in GetAllEmbeddedComponents())
            {
                bool bInstall = true;
                if (bInstalledCompsFound)
                {
                    int nIndex = Common.GetIndexForComponentUniqueLabel(component.UniqueLabel, GetAllInstalledComponents());
                    if (nIndex != -1)
                        bInstall = (GetAllInstalledComponents()[nIndex].CompareTo(component) != 0);
                }

                // mark component for Installation 
                if (bInstall)
                {                    
                    string asmName = "Component.Setup." + component.UniqueLabel;                    
                    _componentsLoaded[component.UniqueLabel] = Assembly.Load(asmName);                 
                }                    
            }

            List<IInstallComponent> ComponentsToInstall = new List<IInstallComponent>();
            if (_componentsLoaded.Count > 0)
            {
                foreach (Assembly asm in _componentsLoaded.Values)
                {
                    IInstallComponent installComp = null;
                    Type[] types = asm.GetTypes();
                    foreach (Type t in types)
                    {
                        if (t.GetInterface(typeof(IInstallComponent).Name) != null)
                        {
                            installComp = (IInstallComponent)asm.CreateInstance(t.FullName);
                            break;
                        }
                    }

                    // Check IInstallComponent was found
                    if (installComp == null)
                    {
                        Common.Log.Error(String.Format("Component {0} contains no IInstallComponent Definition.", AssemblyW.GetAssemblyName(asm)));
                        continue;
                    }

                    // Check if class also implements ISetup
                    if (installComp is ISetup)
                        ((ISetup)installComp).ComponentLoaded(ref setupEventObj);

                    // Add to Install Components
                    ComponentsToInstall.Add(installComp);
                }
            }
            return ComponentsToInstall.ToArray();          
        }

        /// <summary>
        /// Retrieves the list of all installed components, in order to uninstall
        /// </summary>
        /// <returns>a list of all installed components, null otherwise</returns>
        public IInstallComponent[] GetAllInstalledComponents(string ComponentsSeperatedbySemiColonOrBlankForAll, ref SetupEvents setupEventObj)
        {
            // TO DO:

            //string[] ComponentsUniqueLabels = null;
            //if (!String.IsNullOrEmpty(ComponentsSeperatedbySemiColonOrBlankForAll))
            //    ComponentsUniqueLabels = ComponentsSeperatedbySemiColonOrBlankForAll.Split(';');            
            return null;
        }

        /// <summary>
        /// Retrieves the list of all installed components
        /// </summary>
        /// <returns>a list of all installed components, null otherwise</returns>
        public ComponentConfig.Component[] GetAllInstalledComponents()
        {
            if (Common.InstalledConfig != null && Common.InstalledConfig.SetupComponents.Components.Length > 0)
                return Common.InstalledConfig.SetupComponents.Components;
            return null;
        }

        /// <summary>
        /// Retrieves the list of all installed componentsW
        /// </summary>
        /// <returns>a list of all installed componentsW, null otherwise</returns>
        public ComponentConfig.ComponentW GetAllInstalledComponentsW()
        {            
            return Common.InstalledConfig.SetupComponents;         
        }

        /// <summary>
        /// Retrieves the list of all Embedded components
        /// </summary>
        /// <returns>a list of all embedded components, null otherwise</returns>
        public ComponentConfig.Component[] GetAllEmbeddedComponents()
        {
            if (Common.EmbeddedConfig != null && Common.EmbeddedConfig.SetupComponents.Components.Length > 0)
                return Common.EmbeddedConfig.SetupComponents.Components;
            return null;
        }  

        #endregion

        #region IDisposable Members

        /// <summary>
        /// Dispose of all extracted files
        /// </summary>
        public void Dispose()
        {
            Dispose(true);

            // Use SupressFinalize in case a subclass
            // of this type implements a finalizer
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Make sure to conserve disk space, to delete all files that were extracted
        /// by this program
        /// </summary>
        /// <param name="disposing">if true, delete all files extracted by this dll</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _componentsLoaded.Clear();
                    _componentsLoaded = null;
                }

                // Indicate that the instance has been disposed.                                                
                _disposed = true;
            }
        }

        #endregion
    }
}
