using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ClipClop.User;
using System.Diagnostics;
using System.IO;
using System.Threading;
using ClipClop.Model;


namespace ClipClop.View
{
	public partial class GoogleDocumentsForm : Form
	{
		static readonly char[] TOKEN_ = {','};

		enum TabName
		{
			account, document
		}

		private ListView.ListViewItemCollection listViewItemCollection_; 
		private ListView.SelectedIndexCollection listViewItemSelection_;

		#region Google Documents
		GData gData_ = new GData();
		#endregion

		public string TempFilePath
		{
			get
			{
				return gData_.TempFilePath;
			}
		}


		public GoogleDocumentsForm()
		{
			InitializeComponent();

			listViewItemCollection_ = new ListView.ListViewItemCollection(this.listView);
			listViewItemSelection_ = new ListView.SelectedIndexCollection(this.listView);

			listView.View = System.Windows.Forms.View.Details;
			listView.VirtualMode = true;
		}

		private void GoogleDocumentsForm_Load(object sender, EventArgs e)
		{
			UpdatePage1(true);

			UpdatePage2(false);

			if( !string.IsNullOrEmpty(Properties.Settings.Default.googleAccountNames))
			{
				string[] usernames = Properties.Settings.Default.googleAccountNames.Split(TOKEN_, StringSplitOptions.RemoveEmptyEntries);
				comboBoxYousername.Items.AddRange(usernames);			
			}

			tabControl.SelectedIndex = (int)TabName.account;
		}

		public void UpdatePage1(bool enable)
		{
			comboBoxYousername.Enabled = enable;
			textBoxPassword.Enabled = enable;

			if( enable )
				buttonLoginout.Text = Properties.Resources.BtnLogin;
			else
				buttonLoginout.Text = Properties.Resources.BtnLogoff;
		}

		public void UpdatePage2(bool enable)
		{
			listView.Enabled = enable;
			if( enable == false )
			{
				listView.Items.Clear();
			}

			buttonImport.Enabled = enable;
			buttonRefresh.Enabled = enable;
		}

		private void buttonLogin_Click(object sender, EventArgs e)
		{
			if (gData_.IsLogin)
			{
				gData_.Logoff();

				UpdatePage1(true);
				UpdatePage2(false);
				return;
			}

			if (string.IsNullOrEmpty(comboBoxYousername.Text))
			{
				Util.ShowWarn(Properties.Resources.MSG010);
				comboBoxYousername.Focus();
				return;
			}
			if (string.IsNullOrEmpty(textBoxPassword.Text))
			{
				Util.ShowWarn(Properties.Resources.MSG011);
				textBoxPassword.Focus();
				return;
			}

			this.Cursor = Cursors.WaitCursor;

			listView.VirtualListSize = 0;

			gData_.SetCredentials(comboBoxYousername.Text, textBoxPassword.Text);

			//ログインする
			backgroundWorkerLogIn.RunWorkerAsync(gData_);
		}




		private void buttonImport_Click(object sender, EventArgs e)
		{
			if (gData_.IsLogin == false)
			{
				return;
			}

			int idx = listViewItemSelection_[0];

			gData_.TargetIndex = idx;

			this.Cursor = Cursors.WaitCursor;

			backgroundWorkerImport.RunWorkerAsync(gData_);
		}


		void AddUsernameToHistory(string newName)
		{
			if (!string.IsNullOrEmpty(Properties.Settings.Default.googleAccountNames))
			{
				string[] usernames = Properties.Settings.Default.googleAccountNames.Split(TOKEN_, StringSplitOptions.RemoveEmptyEntries);

				foreach (string s in usernames)
				{
					if (s.Equals(newName))
						return;
				}
				Properties.Settings.Default.googleAccountNames += TOKEN_ + newName;
			}
			else
			{
				Properties.Settings.Default.googleAccountNames = newName;
			}
		}

		private void listView_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
		{
			if (gData_.Count > e.ItemIndex)
			{
				//名前,種別,フォルダ
				string[] s = gData_.GetDocumentInfo(e.ItemIndex);
				e.Item = new ListViewItem(s);
			}
		}

		private void listView_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e)
		{
			//Trace.WriteLine(string.Format("VirtualItemsSelectionRangeChanged Select:{0} Item:{1}", listViewItemSelection_.Count, listViewItemCollection_.Count));
		}

		private void listView_SelectedIndexChanged(object sender, EventArgs e)
		{
			Trace.WriteLine(string.Format("SelectedIndexChanged {0}-{1}", listViewItemSelection_.Count, listViewItemCollection_.Count));
			
			UpdateButton();
		}

		void UpdateButton()
		{
			if (listViewItemSelection_.Count > 0)
			{
				int idx = listViewItemSelection_[0];
				if (gData_.Count > idx)
				{
					if ( gData_.IsDownloadable(idx))
					{
						//XMLファイルはunknownになるらしい
						buttonImport.Enabled = true;
						return;
					}
				}
			}
			buttonImport.Enabled = false;
		}

		private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			GData gdata = (GData)e.Argument;

			gdata.Login();
		}

		private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			this.Cursor = Cursors.Default;

			if (!gData_.IsLogin)
			{
				if( gData_.Excep != null )
					Util.ShowError(gData_.Excep);
				return;
			}

			if (gData_.Excep != null)
				Util.ShowError(gData_.Excep);

			AddUsernameToHistory(comboBoxYousername.Text);

			listView.VirtualListSize = gData_.Count;

			UpdatePage1(false);
			UpdatePage2(true);

			tabControl.SelectedIndex = (int)TabName.document;
			UpdateButton();
		}

		private void backgroundWorkerImport_DoWork(object sender, DoWorkEventArgs e)
		{
			GData gdata = (GData)e.Argument;

			gdata.Import();

		}

		private void backgroundWorkerImport_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			this.Cursor = Cursors.Default;

			if (gData_.Excep != null)
			{
				Util.ShowError(gData_.Excep.Message);
				return;
			}


			this.DialogResult = DialogResult.OK;
			this.Close();
		}

		private void buttonRefresh_Click(object sender, EventArgs e)
		{
			if (gData_.IsLogin == false)
			{
				return;
			}

			gData_.TargetIndex = -1;

			this.Cursor = Cursors.WaitCursor;

			listView.VirtualListSize = 0;

			backgroundWorkerRefresh.RunWorkerAsync(gData_);

		}

		private void backgroundWorkerRefresh_DoWork(object sender, DoWorkEventArgs e)
		{
			GData gdata = (GData)e.Argument;

			gdata.Refresh();
		}

		private void backgroundWorkerRefresh_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			this.Cursor = Cursors.Default;

			listView.VirtualListSize = gData_.Count;

			if (gData_.Excep != null)
			{
				Util.ShowError(gData_.Excep.Message);
				return;
			}


			UpdateButton();
		}


	}
}
