using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace EQTrack
{
	public partial class MainForm : Form
	{
		public CustomPanel mLastPanel;
		private CustomPanel mCurrentPanel;
		private Timer AnimateTimer;

		public bool AnimateDirectionLeft = true;

		public MainForm()
		{
			InitializeComponent();

			// Load Local Settings
			Globals.Settings.Load(Globals.SettingsFilename);

			// Initialise all the CustomPanels and web services
			Globals.Initialize();

            Globals.htOptions.Add("FUN", Globals.Settings.GetString(Globals.SettingsPathOptions + "FUN", "1"));
            Globals.htOptions.Add("Min_LAT", Globals.Settings.GetString(Globals.SettingsPathOptions + "Min_LAT", ""));
            Globals.htOptions.Add("Max_LAT", Globals.Settings.GetString(Globals.SettingsPathOptions + "Max_LAT", ""));
            Globals.htOptions.Add("Min_LON", Globals.Settings.GetString(Globals.SettingsPathOptions + "Min_LON", ""));
            Globals.htOptions.Add("Max_LON", Globals.Settings.GetString(Globals.SettingsPathOptions + "Max_LON", ""));
            Globals.htOptions.Add("Min_Battery", Globals.Settings.GetString(Globals.SettingsPathOptions + "Min_Battery", "12.0"));
            Globals.htOptions.Add("Max_Battery", Globals.Settings.GetString(Globals.SettingsPathOptions + "Max_Battery", "15.0"));
            Globals.htOptions.Add("Min_FIX", Globals.Settings.GetString(Globals.SettingsPathOptions + "Min_FIX", "3"));
            Globals.htOptions.Add("Min_SSI", Globals.Settings.GetString(Globals.SettingsPathOptions + "Min_SSI", "8"));
            Globals.htOptions.Add("SWV", Globals.Settings.GetString(Globals.SettingsPathOptions + "SWV", "703406006"));
            Globals.htOptions.Add("Database", Globals.Settings.GetString(Globals.SettingsPathOptions + "Database", "Blackhawk.mdb"));
            Globals.htOptions.Add("ChkFactoryDB", Globals.Settings.GetBool(Globals.SettingsPathOptions + "ChkFactoryDB", false));
            Globals.htOptions.Add("Max_Units", Globals.Settings.GetInt(Globals.SettingsPathOptions + "Max_Units", 500));

			// Add all the CustomPanels
            AddPanel(Globals.MainMenuForm.MainPanel);
            AddPanel(Globals.DeviceEventsForm.MainPanel);
			AddPanel(Globals.LoginForm.MainPanel);
            
			mCurrentPanel.BringToFront();
			AnimateTimer = new Timer();
			AnimateTimer.Interval = 20;
			AnimateTimer.Tick += new EventHandler(AnimateTimer_Tick);
		}

		private void MainForm_Load(object sender, EventArgs e)
		{
			// Appearance
			if (Globals.Settings.GetBool(Globals.SettingsPathAppearance + "WindowIsMaximized", false))
			{
				this.WindowState = FormWindowState.Maximized;
			}
			else
			{
				this.Location = new Point(Globals.Settings.GetInt(Globals.SettingsPathAppearance + "WindowLeft", this.Left),
												  Globals.Settings.GetInt(Globals.SettingsPathAppearance + "WindowTop", this.Top));
				this.Size = new Size(Globals.Settings.GetInt(Globals.SettingsPathAppearance + "WindowWidth", this.Width),
											Globals.Settings.GetInt(Globals.SettingsPathAppearance + "WindowHeight", this.Height));
			}

			Timer StartupTimer = new Timer();
			StartupTimer.Interval = 50;
			StartupTimer.Tick += new EventHandler(StartupTimer_Tick);
			StartupTimer.Enabled = true;
		}

		void StartupTimer_Tick(object sender, EventArgs e)
		{
			((Timer)sender).Enabled = false;

			// Start Login Panel
			mCurrentPanel.Initialise(this, null);
		}

		private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			//Globals.EventManagerForm.StopUpdates();

			// Dispose all CustomPanels - each one saves their own settings
			Globals.Dispose();

			// Main Form size and location
			Globals.Settings.Set(Globals.SettingsPathAppearance + "WindowIsMaximized", this.WindowState == FormWindowState.Maximized);
			if (this.WindowState != FormWindowState.Maximized)
			{
				Globals.Settings.Set(Globals.SettingsPathAppearance + "WindowTop", this.Top);
				Globals.Settings.Set(Globals.SettingsPathAppearance + "WindowLeft", this.Left);
				Globals.Settings.Set(Globals.SettingsPathAppearance + "WindowWidth", this.Width);
				Globals.Settings.Set(Globals.SettingsPathAppearance + "WindowHeight", this.Height);
			}

			Globals.Settings.Save(Globals.SettingsFilename);

			// Close Databases
			AccessDatabase.CloseDatabase();
		}

		private void AddPanel(CustomPanel ThisPanel)
		{
			BasePanel.Controls.Add(ThisPanel);
			ThisPanel.Dock = DockStyle.None;
			ThisPanel.Size = BasePanel.Size;
			mCurrentPanel = ThisPanel;
		}

		public CustomPanel CurrentPanel
		{
			get
			{
				return mCurrentPanel;
			}
			set
			{
				if (mCurrentPanel != value)
				{
					mLastPanel = mCurrentPanel;
					mCurrentPanel = value;
					mLastPanel.Finish(this, null);

					if (AnimateDirectionLeft)
						mCurrentPanel.Left = this.ClientSize.Width;
					else
						mCurrentPanel.Left = -this.ClientSize.Width;
					mCurrentPanel.BringToFront();
					mCurrentPanel.Initialise(this, null);
					AnimateTimer.Enabled = true;
				}
			}
		}

		void AnimateTimer_Tick(object sender, EventArgs e)
		{
			AnimateTimer.Enabled = false;
			if ((AnimateDirectionLeft && mCurrentPanel.Left > 0) || (!AnimateDirectionLeft && mCurrentPanel.Left < 0))
			{
				int MoveAmount = AnimateDirectionLeft ? this.ClientSize.Width / 6 : -this.ClientSize.Width / 6;
				if ((AnimateDirectionLeft && mCurrentPanel.Left < MoveAmount) || (!AnimateDirectionLeft && mCurrentPanel.Left > MoveAmount))
					MoveAmount = mCurrentPanel.Left;
				mCurrentPanel.Left = mCurrentPanel.Left - MoveAmount;
				mLastPanel.Left = mLastPanel.Left - MoveAmount;
				AnimateTimer.Enabled = true;
			}
			else
				mCurrentPanel.Enabled = true;
		}

		private void Form1_Resize(object sender, EventArgs e)
		{
			foreach (Control ThisControl in BasePanel.Controls)
				ThisControl.Size = BasePanel.Size;
		}
	}


	public class Globals
	{
		public static MainForm MainForm = null;
		public static LoginForm LoginForm = null;
		public static MainMenuForm MainMenuForm = null;
        public static DeviceEventsForm DeviceEventsForm = null;
        


        

		public static XMLSettings Settings = new XMLSettings("BlackhawkSettings");

		public static string SettingsFilename = Application.StartupPath + "\\EQTrackSettings.config";
		public static string SettingsPathAppearance = "Appearance\t";
		public static string SettingsPathSetup = "Setup\t";
		public static string SettingsPathLogin = "Login\t";
		public static string SettingsPathEvents = "Events\t";
		public static string SettingsPathOptions = "Options\t";
		public static string SettingsPathDatabase = "Database\t";

		public static int CustomerID = 0;
        public static string UserName = "";
        

		public static System.Net.CookieContainer CookieContainer = new System.Net.CookieContainer();
		public static string LoginServiceUrl = "";
		public static string WebServicesUrl = "";
		public static BlackhawkLoginService.CorporateLogin LoginService;
		public static BlackhawkTrackService.TrackService TrackService;
		public static BlackhawkEventService.EventService EventService;
		public static BlackhawkAdminService.AdminService AdminService;
        public static BlackhawkDeviceSetService.DeviceSetService DeviceSetService;
		public static BlackhawkDeviceService.DeviceService DeviceService;
        public static BlackhawkSMSService.SMSService SMSService;

        public static BlackhawkFactoryService.FactoryService FactoryService;
        public static BlackhawkInvoiceService.InvoiceService InvoiceService;
        public static BlackhawkReportService.ReportService ReportService;
        public static Hashtable htOptions = new Hashtable();
        public static bool resetPassed = false;
        public static bool csvCreated = false;

		public class BlackhawkEventItem
		{
			public int ID;
			public DateTime EventTime;
			public int FunctionNumber;
			public string SerialNumber;
			public string Location;
			public string LatLng;

			public object Tag = null;

			public BlackhawkEventItem(int ID, DateTime EventTime, int FunctionNumber, string SerialNumber, string Location, string LatLng)
			{
				this.ID = ID;
				this.EventTime = EventTime;
				this.FunctionNumber = FunctionNumber;
				this.SerialNumber = SerialNumber;
				this.Location = Location;
				this.LatLng = LatLng;
			}
		}

		public class BlackhawkEvent : List<BlackhawkEventItem>
		{
			public int FunctionNumber;
			public string Description;

			public BlackhawkEvent(int FunctionNumber, string Description)
			{
				this.FunctionNumber = FunctionNumber;
				this.Description = Description;
			}
		}

		public class BlackhawkEvents : List<BlackhawkEvent>
		{
			public BlackhawkEvent Find(int FunctionNumber)
			{
				foreach (BlackhawkEvent ThisEvent in this)
				{
					if (ThisEvent.FunctionNumber == FunctionNumber)
						return ThisEvent;
				}
				return null;
			}

			public BlackhawkEvent Find(string Description)
			{
				foreach (BlackhawkEvent ThisEvent in this)
				{
					if (ThisEvent.Description == Description)
						return ThisEvent;
				}
				return null;
			}

			public void AddItem(int FunctionNumber, int ID, DateTime EventTime, string SerialNumber, string Location, string LatLng)
			{
				BlackhawkEvent ThisEvent = Find(FunctionNumber);
				if (ThisEvent != null)
					ThisEvent.Add(new BlackhawkEventItem(ID, EventTime, FunctionNumber, SerialNumber, Location, LatLng));
			}

			public void ClearItems()
			{
				foreach (BlackhawkEvent ThisEvent in this)
					ThisEvent.Clear();
			}
		}

		public static BlackhawkEvents BlackhawkEventList = new BlackhawkEvents();

		public static void Initialize()
		{
			LoginServiceUrl = Globals.Settings.GetString(Globals.SettingsPathSetup + "WebServiceUrl", "http://www.bhtrack.net/BlackhawkAPI/");
			Globals.Settings.Set(Globals.SettingsPathSetup + "WebServiceUrl", LoginServiceUrl);
			WebServicesUrl = LoginServiceUrl + "/WebServices";
			CookieContainer = new System.Net.CookieContainer();
			
			//System.Net.WebRequest.DefaultWebProxy.Credentials = new System.Net.NetworkCredential("sidh", "Studio12", "ACTRONIC");

			LoginService = new EQTrack.BlackhawkLoginService.CorporateLogin();
			//LoginService.Url = LoginServiceUrl + "/Login.asmx";
			LoginService.Url = WebServicesUrl + "/Login.asmx";
			LoginService.Credentials = System.Net.CredentialCache.DefaultCredentials;
			LoginService.CookieContainer = Globals.CookieContainer;
			LoginService.Timeout = 10000; // 10 seconds

			TrackService = new EQTrack.BlackhawkTrackService.TrackService();
			TrackService.Url = WebServicesUrl + "/TrackService.asmx";
			TrackService.Credentials = System.Net.CredentialCache.DefaultCredentials;
			TrackService.CookieContainer = Globals.CookieContainer;

			EventService = new EQTrack.BlackhawkEventService.EventService();
			EventService.Url = WebServicesUrl + "/EventService.asmx";
			EventService.Credentials = System.Net.CredentialCache.DefaultCredentials;
			EventService.CookieContainer = Globals.CookieContainer;

			AdminService = new EQTrack.BlackhawkAdminService.AdminService();
			AdminService.Url = WebServicesUrl + "/AdminService.asmx";
			AdminService.Credentials = System.Net.CredentialCache.DefaultCredentials;
			AdminService.CookieContainer = Globals.CookieContainer;

			DeviceSetService = new EQTrack.BlackhawkDeviceSetService.DeviceSetService();
            DeviceSetService.Url = WebServicesUrl + "/DeviceSetService.asmx";
            DeviceSetService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            DeviceSetService.CookieContainer = Globals.CookieContainer;

			DeviceService = new EQTrack.BlackhawkDeviceService.DeviceService();
			DeviceService.Url = WebServicesUrl + "/DeviceService.asmx";
			DeviceService.Credentials = System.Net.CredentialCache.DefaultCredentials;
			DeviceService.CookieContainer = Globals.CookieContainer;

            FactoryService = new EQTrack.BlackhawkFactoryService.FactoryService();
            FactoryService.Url = WebServicesUrl + "/FactoryService.asmx";
            FactoryService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            FactoryService.CookieContainer = Globals.CookieContainer;

            InvoiceService = new EQTrack.BlackhawkInvoiceService.InvoiceService();
            InvoiceService.Url = WebServicesUrl + "/InvoiceService.asmx";
            InvoiceService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            InvoiceService.CookieContainer = Globals.CookieContainer;

            ReportService = new EQTrack.BlackhawkReportService.ReportService();
            ReportService.Url = WebServicesUrl + "/ReportService.asmx";
            ReportService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            ReportService.CookieContainer = Globals.CookieContainer;

			LoginForm = new LoginForm();
			MainMenuForm = new MainMenuForm();
            DeviceEventsForm = new DeviceEventsForm();
        }


		public static void Dispose()
		{
			DeviceService.Dispose();
			DeviceSetService.Dispose();
			AdminService.Dispose();
			TrackService.Dispose();
			EventService.Dispose();
			LoginService.Dispose();

			LoginForm.Dispose();
			MainMenuForm.Dispose();
            DeviceEventsForm.Dispose(); 

		
		}

		public static string GetTimeAgoString(DateTime ThisDateTime)
		{
			TimeSpan TimeDiff = (DateTime.Now - ThisDateTime);
			if (TimeDiff.TotalMinutes < 1)
				return "<1 min ago";
			else if (TimeDiff.TotalHours < 1)
				return ((int)TimeDiff.TotalMinutes).ToString() + " min ago";
			else if (TimeDiff < (DateTime.Now - DateTime.Now.Date))
				return ((int)TimeDiff.TotalHours).ToString() + " hr " + TimeDiff.Minutes.ToString() + " min ago";
			else if (ThisDateTime.Date.AddDays(1) == DateTime.Now.Date)
				return "Yesterday " + ThisDateTime.ToShortTimeString();
			else
				return ThisDateTime.ToShortDateString() + " " + ThisDateTime.ToShortTimeString();
		}
	}
}