using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using PXP.Crawler.Loader.Utils;
using SplashScreen;

namespace PXP.Crawler.Loader
{
    static class Program
    {
        public static string exePath;


        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            exePath = Application.ExecutablePath;
            exePath = exePath.Substring(0, exePath.LastIndexOf('\\')) + '\\';

            Process curProc = Process.GetCurrentProcess();
            Process mfProcess = null;
            foreach (Process cpr in Process.GetProcesses())
            {
                Debug.WriteLine(cpr.ProcessName);
                if (cpr.ProcessName.Contains("PXP") && cpr.ProcessName.Contains("Crawler") && !cpr.ProcessName.Contains("Loader"))
                {
                    if (cpr.MainWindowTitle == "PXP Crawler")
                    {
                        mfProcess = cpr;
                        break;
                    }
                }
            }

            string[] args = Environment.GetCommandLineArgs();

            // Parsiraj argumente komandne linije...

            string openFileName = "";

            if (args.Length > 1)
            {
                openFileName = args[1];
            }

            if (mfProcess != null)
            {
                if (openFileName.Length > 0)
                {
                    Process mfProc = mfProcess;

                    string addStr = "Test";
                    IntPtr addStrPtr = Marshal.StringToHGlobalUni(addStr);

                    Win32.COPYDATASTRUCT cd = new Win32.COPYDATASTRUCT()
                    {
                        dwData = 0,
                        cbData = addStr.Length * 2,
                        lpData = addStrPtr
                    };

                    IntPtr lpAddStruct = Marshal.AllocHGlobal(Marshal.SizeOf(cd));

                    Marshal.StructureToPtr(cd, lpAddStruct, false);
                    Win32.SendMessage(mfProc.MainWindowHandle, (int)Win32.WindowsMessage.COPYDATA,
                        Process.GetCurrentProcess().MainWindowHandle, lpAddStruct);
                    Marshal.FreeHGlobal(lpAddStruct);                    
                }
            }
            else
            {
                string prFile = exePath + "PXP.Crawler.exe";
                Process crProc = Process.Start(new ProcessStartInfo(prFile) {WorkingDirectory = exePath, UseShellExecute = true});                
            }



            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.Run(new SplashForm());}
    }}
