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


namespace Sync
{
	public partial class frmSync : Form
	{
		private List<FileCompare> _CheckedOut;
		private bool IsLoading = false;
		public frmSync()
		{
			InitializeComponent();
		}
		private void LoadSettings()
		{
			if (Properties.Settings.Default["Location"] != null)
				Location = Properties.Settings.Default.Location;
			if (Properties.Settings.Default["Size"] != null)
				Size = Properties.Settings.Default.Size;
			if (Properties.Settings.Default.DevelopmentFolder != "")
				tbDevelopment.Text = Properties.Settings.Default.DevelopmentFolder;
			if (Properties.Settings.Default.SourceSafeFolder != "")
				tbSourceSafe.Text = Properties.Settings.Default.SourceSafeFolder;
			if(Properties.Settings.Default.MailBoxDevelopmentFolder != "")
				tbMailBox.Text = Properties.Settings.Default.MailBoxDevelopmentFolder;
			if (Properties.Settings.Default.MailBoxSourceSafeFolder != "")
				tbSSMailBox.Text = Properties.Settings.Default.MailBoxSourceSafeFolder;
		}
		private void frmSync_Load(object sender, EventArgs e)
		{
			LoadSettings();
			Setup();
		}
		private void Setup()
		{
			// Setup Browse Buttons
			btnBrwsDev.Tag = this.tbDevelopment;
			btnBrwsSS.Tag = this.tbSourceSafe;
			btnBrwsMail.Tag = this.tbMailBox;
			btnBrwsSSMail.Tag = this.tbSSMailBox;
		}
		private void btnBrowse_Click(object sender, EventArgs e)
		{
			TextBox tb = (TextBox)((Button)sender).Tag;
			fbd.SelectedPath = tb.Text;
			if (fbd.ShowDialog() == DialogResult.OK)
				tb.Text = fbd.SelectedPath;
		}
		private void ClearResults()
		{
			_CheckedOut = new List<FileCompare>();
		}
		private void FindCheckedOut(DirectoryInfo di)
		{
			FindCheckedOut(di.GetFiles());
			FindCheckedOut(di.GetDirectories());
		}
		private void FindCheckedOut(DirectoryInfo[] directoryInfoList)
		{
			foreach (DirectoryInfo di in directoryInfoList)
				FindCheckedOut(di);
		}
		private void FindCheckedOut(FileInfo[] fileInfoList)
		{
			foreach (FileInfo fi in fileInfoList)
				FindCheckedOut(fi);
		}
		private void FindCheckedOut(FileInfo fi)
		{
			if (fi.Name.ToLower().EndsWith("scc")) return;
			if (fi.Name.ToLower().EndsWith("sln")) return;
			if (fi.Name.ToLower().EndsWith("csproj")) return;
			if (fi.Name.ToLower().EndsWith("licx")) return;
			FileInfo fi1 = new FileInfo(fi.FullName.Replace(tbSourceSafe.Text, tbDevelopment.Text));
			if ((fi1.Attributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
				AddToResults(fi, fi1);
		}
		private void AddToResults(FileInfo fiSS,FileInfo fiDev)
		{
			FileCompare fc = new FileCompare(fiDev, fiSS);
			if(!_OnlyContentDifferent || (fc.Different && (fc.DevModified != null)))
				_CheckedOut.Add(fc);
			//if (tbResults.Text == "") tbResults.Text = "Found:";
			//tbResults.Text += "\r\n" + fiDev.FullName + " - " + ((fiDev.Attributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly ? "" : "ReadOnly");
		}
		private void ClearMailBox()
		{
			DeleteFolder(new DirectoryInfo(tbMailBox.Text));
			DeleteFolder(new DirectoryInfo(tbSSMailBox.Text));
		}
		private void DeleteFolder(DirectoryInfo directoryInfo)
		{
			if (directoryInfo.Exists)
			{
				AdjustAttributes(directoryInfo);
				directoryInfo.Delete(true);
			}
		}
		private void AdjustAttributes(DirectoryInfo directoryInfo)
		{
			foreach (DirectoryInfo di in directoryInfo.GetDirectories())
				AdjustAttributes(di);
			foreach (FileInfo fi in directoryInfo.GetFiles())
				AdjustAttribute(fi);
		}
		private void AdjustAttribute(FileInfo fi)
		{
			if ((fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
				fi.Attributes = fi.Attributes ^ FileAttributes.ReadOnly;
		}
		private void frmSync_FormClosing(object sender, FormClosingEventArgs e)
		{
			Properties.Settings.Default.Location = Location;
			Properties.Settings.Default.Size = Size;
			Properties.Settings.Default.DevelopmentFolder = tbDevelopment.Text;
			Properties.Settings.Default.SourceSafeFolder = tbSourceSafe.Text;
			Properties.Settings.Default.MailBoxDevelopmentFolder = tbMailBox.Text;
			Properties.Settings.Default.MailBoxSourceSafeFolder = tbSSMailBox.Text;
			Properties.Settings.Default.Save();
		}
		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.Close();
		}
		private void clearToolStripMenuItem_Click(object sender, EventArgs e)
		{
			ClearMailBox();
		}
		private void buildToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			ClearMailBox();
			if (_CheckedOut == null)
				checkedOutToolStripMenuItem_Click(sender, e);
			foreach (FileCompare fc in _CheckedOut)
			{
				if (fc.ToProcess)
				{
					fc.MoveDevToMailBox(tbDevelopment.Text, tbMailBox.Text);
					fc.MoveSSToMailBox(tbSourceSafe.Text, tbSSMailBox.Text);
				}
			}
		}
		private void checkedOutToolStripMenuItem_Click(object sender, EventArgs e)
		{
			ClearResults();
			// Walk though Source Safe and check to see if the files in the Development folder are read-only
			FindCheckedOut(new DirectoryInfo(tbSourceSafe.Text));
			dgv.DataSource = _CheckedOut;
			SetColumnWidth();
		}
		private void syncAllToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			foreach (FileCompare fc in _CheckedOut)
			{
				fc.MoveToDevelopment();
			}
		}
		private void restoreUnchangedToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			foreach (FileCompare fc in _CheckedOut)
			{
				if(!fc.Different || fc.DevModified == null)
					fc.MoveToDevelopment();
			}
		}
		private void restoreSelectedToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			foreach (FileCompare fc in _CheckedOut)
			{
				if (fc.ToProcess) fc.MoveToDevelopment();
			}
		}
		private void restoreAllToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			foreach (FileCompare fc in _CheckedOut)
			{
				fc.MoveToDevelopment();
			}
		}
		private List<FileCompare> SelectedList
		{
			get
			{
				dgv.EndEdit();
				List<FileCompare> fcList = new List<FileCompare>();
				foreach (DataGridViewCell dgc in dgv.SelectedCells)
				{
					FileCompare fc = dgv.Rows[dgc.RowIndex].DataBoundItem as FileCompare;
					if (fc != null && fcList.Contains(fc) == false)
						fcList.Add(fc);
				}
				return fcList;
			}
		}
		private void compareToolStripMenuItem_Click(object sender, EventArgs e)
		{
			// This should launch UltraCompare with the two files
			// Which Item am I on
			List<FileCompare> fcList = SelectedList;
			foreach (FileCompare fc in fcList)
			{
				Console.WriteLine("Compare {0} and {1}", fc.FileName, fc.SSFileName);
				string cmd = string.Format("\"C:\\Program Files\\IDM Computer Solutions\\UltraCompare\\UC.exe\" -t \"{0}\" \"{1}\"", fc.FileName, fc.SSFileName);
				System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files\IDM Computer Solutions\UltraCompare\UC.exe",
					string.Format(@" -t ""{0}"" ""{1}""", fc.FileName, fc.SSFileName));
				System.Diagnostics.Process prc = System.Diagnostics.Process.Start(psi);
			}
		}
		private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
		{
			List<FileCompare> fcList = SelectedList;
			foreach (FileCompare fc in fcList)
			{
				fc.MoveToDevelopment();
			}
		}
		private void differentToolStripMenuItem_Click(object sender, EventArgs e)
		{
			ClearResults();
			// Walk though Source Safe and check to see if the files in the Development folder are read-only
			FindDifferent(new DirectoryInfo(tbSourceSafe.Text));
			dgv.DataSource = _CheckedOut;
			SetColumnWidth();
		}
		private void SetColumnWidth()
		{
			IsLoading = true;
			if (Properties.Settings.Default["Widths"] == null)
			{
				dgv.Columns[0].Width = 60;
				dgv.Columns[1].Visible = false;
				dgv.Columns[2].Width = 125;
				dgv.Columns[3].Width = 125;
				dgv.Columns[4].Width = 50;
				dgv.Columns[5].Width = 500;
			}
			else
			{
				for (int i = 0; i < Properties.Settings.Default.Widths.Count; i++)
				{
					string sWidth = Properties.Settings.Default.Widths[i];
					if (sWidth == "Invisible")
						dgv.Columns[i].Visible = false;
					else
						dgv.Columns[i].Width = int.Parse(sWidth);
				}
			}
			dgv.Columns[1].Visible = false;
			IsLoading = false;
		}
		private void FindDifferent(DirectoryInfo di)
		{
			FindDifferent(di.GetFiles());
			FindDifferent(di.GetDirectories());
		}
		private void FindDifferent(DirectoryInfo[] directoryInfoList)
		{
			foreach (DirectoryInfo di in directoryInfoList)
				FindDifferent(di);
		}
		private void FindDifferent(FileInfo[] fileInfoList)
		{
			foreach (FileInfo fi in fileInfoList)
				FindDifferent(fi);
		}
		private void FindDifferent(FileInfo fi)
		{
			if (fi.Name.ToLower().EndsWith("scc")) return;
			if (fi.Name.ToLower().EndsWith("sln")) return;
			if (fi.Name.ToLower().EndsWith("csproj")) return;
			if (fi.Name.ToLower().EndsWith("licx")) return;
			FileInfo fiD = new FileInfo(fi.FullName.Replace(tbSourceSafe.Text, tbDevelopment.Text));
			FileInfo fiS = fi;
			// Only check Read-Only flag, other attributes are unimportant
			if (fiS.LastWriteTimeUtc != fiD.LastWriteTimeUtc || (fiS.Attributes & FileAttributes.ReadOnly ) != (fiD.Attributes & FileAttributes.ReadOnly ))
				AddToResults(fi, fiD);
		}
		private void dgv_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
		{
			if (!IsLoading)
			{
				System.Collections.Specialized.StringCollection widths = new System.Collections.Specialized.StringCollection();
				foreach (DataGridViewColumn col in dgv.Columns)
					widths.Add(col.Visible ? col.Width.ToString() : "Invisible");
				Properties.Settings.Default.Widths = widths;
				Properties.Settings.Default.Save();
			}
		}
		private bool _OnlyContentDifferent = false;
		private void contentDifferentToolStripMenuItem_Click(object sender, EventArgs e)
		{
			ClearResults();
			_OnlyContentDifferent = true;
			// Walk though Source Safe and check to see if the files in the Development folder are read-only
			FindDifferent(new DirectoryInfo(tbSourceSafe.Text));
			_OnlyContentDifferent = false;
			dgv.DataSource = _CheckedOut;
			SetColumnWidth();
		}
		private void frmSync_LocationChanged(object sender, EventArgs e)
		{
			Rectangle rec = Screen.GetWorkingArea(this);
			if (Math.Abs(Left - rec.X) < 10) Left = rec.X;
			if (Math.Abs(Top - rec.Y) < 10) Top = rec.Y;
			if (Math.Abs(rec.X + rec.Width - Right) < 10) Left = rec.X + rec.Width - Width;
			if (Math.Abs(rec.Y + rec.Height - Bottom) < 10) Top = rec.Y + rec.Height - Height;
		}
	}
}