using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.Skins;
using NodePinDirPXP.Crawler.API.Utils;
using PXP.Crawler.API;
using PXP.Crawler.API.Model;
using PXP.Crawler.Forms;
using SplashScreen;

namespace PXP.Crawler
{
    static class Program
    {
        public static MainXtraForm mainForm;
        public static string exePath;
        public static string pluginsPath;

        public static string projectsPath;

        public static PluginManager plugMan;

        public static Sett sett = new Sett(false);

        public static SplashForm splashForm;

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //splashForm = new SplashForm();
            //splashForm.Show();

            exePath = Application.ExecutablePath;
            exePath = exePath.Substring(0, exePath.LastIndexOf('\\')) + '\\';

            pluginsPath = exePath + "Plugins";
            if (!Directory.Exists(pluginsPath))
                Directory.CreateDirectory(pluginsPath);

            pluginsPath += "\\";

            projectsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\PXP Crowler Projects";
            if (!Directory.Exists(projectsPath))
                Directory.CreateDirectory(projectsPath);

            
            DirectoryInfo exeDirInfo = new DirectoryInfo(exePath);
            foreach (FileInfo exeFileInfo in exeDirInfo.GetFiles("PBIN_*.*"))
            {
                File.Delete(exeFileInfo.FullName);
            }            

            Skybound.Gecko.Xpcom.Initialize(exePath + "\\xulrunner");
            
            ProjectCompiler.ReferencesPath = exePath;

            sett.Load(exePath + "settings.xml");

            PluginManager.SetConnectionString(Properties.Settings.Default.SqlConnectionString);
            plugMan = new PluginManager(pluginsPath);
            plugMan.ReferencesPath = exePath;
            plugMan.Initialize();

            SkinManager.EnableFormSkins();

            mainForm = new MainXtraForm();
            sett.LoadControl(mainForm);

            Application.Run(mainForm);

            plugMan.Dispose();

            exeDirInfo = new DirectoryInfo(exePath);
            foreach (FileInfo exeFileInfo in exeDirInfo.GetFiles("PBIN_*.*"))
            {
                try
                {
                    File.Delete(exeFileInfo.FullName);
                }
                catch (Exception exc)
                {
                    
                }
            }            
        }
    }
}
