// clsMain.cs
// Copyright (C) 2008 Karel Jordaan http://zanzi.ops4it.com
// 
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using FileScope;
using FileScope.Gnutella2;
using LibControlLogic.Error;


namespace ZANZILib
{
    /// <summary>
    /// Summary description for clsMain.
    /// </summary>
    public class clsMain
    {
        #region Delegates

        public delegate void SystemLogMessage(string Message);

        #endregion

// delegate declaration
        public static event SystemLogMessage SystemLogMessageEvent;


        #region Functions

        public static void RaiseSystemMessage(string str)
        {
            //SystemLogMessageEvent("Engen started");
            SystemLogMessageEvent(str);
        }

        public void StartEngen()
        {
            SystemLogMessageEvent("Starting Engen ");

            try
            {
                Application.ThreadException += AppError;
                Stats.InitializeVariables();
                Stats.LoadSave.LoadShares();
                Stats.LoadSave.LoadHosts();
                Stats.LoadSave.LoadWebCache();
                Stats.LoadSave.LoadLastFileSet();

                if (Stats.settings.autoGnutella2)
                    StartStop.Start();

                //start listening
                Listener.Start();


                //let everyone know
                Stats.Updated.opened = true;

                G2Data.SetupFuncTable();
                //	FileScope.Gnutella2.Sck.scks[FileScope.Gnutella2.Sck.GetSck()].Reset("192.168.0.100:6000");
                //	FileScope.Gnutella2.Sck.scks[FileScope.Gnutella2.Sck.GetSck()].Reset("192.168.0.50:6000");

                HubInfo hi = new HubInfo();
                MoreHubInfo mhi = new MoreHubInfo();
                hi.mhi = mhi;
                //FileScope.Stats.gnutella2WebCache.Add("http://www20.brinkster.com/dgc2/lynnx.asp", hi);
                //FileScope.Stats.gnutella2WebCache.Add("http://www20.brinkster.com/dgc2/lynnx.asp");
                //						Stats.gnutella2WebCache.Add("http://user1.7host.com/dgwc2/lynnx.asp");
                //						Stats.gnutella2WebCache.Add("http://gwebcache2.jonatkins.com/cgi-bin/gwebcache.cgi");
                //						Stats.gnutella2WebCache.Add("http://www.newsability.com/Services/GWC2/lynn.asp");
                //						Stats.gnutella2WebCache.Add("http://g2cache.theg2.net/gwcache/lynnx.asp");
                //						Stats.gnutella2WebCache.Add("http://gwebcache5.jonatkins.com/cgi-bin/perlgcache.cgi");
                //

                //zzoi 10 mrt 2009 running webcache local
                //http://localhost/cachechu/
                //FileScope.Stats.gnutella2WebCache.Add("http://localhost/cachechu/index.php", hi);

                SystemLogMessageEvent("Engen started");

                
                
            }
            catch (Exception  ex)
            {
                 new clsExeption(ex);
            }
        }

        public void StopEngen()
        {
            try
            {
                //let everyone know we're closing the app
                Stats.Updated.closing = true;
                Stats.StopFSWs();
                //main.search.SerializeSearches();
                //main.trayIcon.Visible = false;
                Listener.Abort();
                ChatManager.DisconnectAll();
                while (DownloadManager.countFinishes != 0)
                    Thread.Sleep(50);
                DownloadManager.StopAllDownloads();
                UploadManager.DisconnectAll();
                //Gnutella.StartStop.Abort();
                StartStop.Stop();
                //OpenNap.StartStop.Stop();
                //EDonkey.StartStop.Stop();
                HashEngine.Stop();
                while (HashEngine.IsAlive())
                    Thread.Sleep(20);
                //FileScope.Stats.LoadSave.SaveSettings();
                Stats.LoadSave.SaveShares();
                Stats.LoadSave.SaveHosts();
                Stats.LoadSave.SaveWebCache();
                Stats.LoadSave.SaveLastFileSet();
                Debug.WriteLine("---exiting---");

                SystemLogMessageEvent("Engen stopped");
                ///ZANZILib.clsMain.RaiseSystemMessage("Engen stopped");
            }
            catch (Exception  ex)
            {
                 new clsExeption(ex);
            }
        }


        #endregion
        /// <summary>
        /// Error somewhere in our app.
        /// </summary>
        private static void AppError(object sender, ThreadExceptionEventArgs args)
        {
            string errmsg = args.Exception.Message + "\r\n" +
                            args.Exception.Source + "\r\n" +
                            args.Exception.StackTrace;

            if (Stats.Updated.closing)
            {
                try
                {
                    FileStream fsClose = new FileStream(Utils.GetCurrentPath("Closing_Errors.txt"),
                                                        FileMode.OpenOrCreate);
                    byte[] elError = Encoding.ASCII.GetBytes(errmsg);
                    fsClose.Write(elError, 0, elError.Length);
                    fsClose.Close();
                }
                catch
                {
                    Debug.WriteLine("AppError");
                }
            }

            //Debug.WriteLine(errmsg);
            //MessageBox.Show(errmsg);
            //Debugger.Break();
        }
    }
}