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;
using System.Xml;
using SevenZip;

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>();
			dgv.DataSource = null;
			Application.DoEvents();
		}
		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"))
			{
				// Find files that have been added to the new Project
				List<string> compileList = GetCompileList(fi.FullName);
				FileInfo fi1csproj = new FileInfo(fi.FullName.Replace(tbSourceSafe.Text, tbDevelopment.Text));
				if (fi1csproj.Exists)
				{
					List<string> compileList1 = GetCompileList(fi1csproj.FullName);
					CompareLists(compileList, compileList1, fi, fi1csproj);
				}
				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 CompareLists(List<string> compileList, List<string> compileList1, FileInfo fi, FileInfo fi1)
		{
			// If anything is in compileList1 and not in CompileList add it to the results
			foreach (string filename in compileList1)
				if (!compileList.Contains(filename))
					AddToResults(fi, fi1, filename);
		}
		private void AddToResults(FileInfo fi, FileInfo fi1, string filename)
		{
			FileInfo newfi = new FileInfo(fi.DirectoryName + "/" + filename);
			FileInfo newfi1 = new FileInfo(fi1.DirectoryName + "/" + filename);
			if(!newfi.Exists)AddToResults(newfi, newfi1); // Only add if the file does not exist
		}
		private List<string> GetCompileList(string fileName)
		{
			List<string> retval = new List<string>();
			XmlDocument doc = new XmlDocument();
			doc.Load(fileName);
			XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
			foreach (XmlAttribute attrib in doc.DocumentElement.Attributes)
				if (attrib.Name == "xmlns")
					nsmgr.AddNamespace("ns", attrib.Value);
			XmlNodeList xl = doc.DocumentElement.SelectNodes(@"//ns:Compile/@Include",nsmgr);
			foreach (XmlAttribute xa in xl)
				retval.Add(xa.Value);
			xl = doc.DocumentElement.SelectNodes(@"//ns:None/@Include", nsmgr);
			foreach (XmlAttribute xa in xl)
				if(xa.Value.ToUpper().EndsWith("SQL"))
					retval.Add(xa.Value);
			xl = doc.DocumentElement.SelectNodes(@"//ns:Content/@Include", nsmgr);
			foreach (XmlAttribute xa in xl)
				if (xa.Value.ToUpper().EndsWith("DLL"))
					retval.Add(xa.Value);
			xl = doc.DocumentElement.SelectNodes(@"//ns:Content/@Include", nsmgr);
			foreach (XmlAttribute xa in xl)
				if (xa.Value.ToUpper().EndsWith("XML"))
					retval.Add(xa.Value);
			xl = doc.DocumentElement.SelectNodes(@"//ns:EmbeddedResource/@Include", nsmgr);
			foreach (XmlAttribute xa in xl)
				if (!xa.Value.ToUpper().EndsWith("LICX"))
					retval.Add(xa.Value);
			return retval;
		}
		private void AddToResults(FileInfo fiSS,FileInfo fiDev)
		{
			FileCompare fc = new FileCompare(fiDev, fiSS);
			//if(!_OnlyContentDifferent || (fc.Different && (fc.DevModified != null)))
				if (!_OnlyContentDifferent || (fc.Different))
					_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)
		{
			fi.Attributes &= (fi.Attributes ^ FileAttributes.ReadOnly);// Turn-Off ReadOnly Attribute
			fi.Attributes &= (fi.Attributes ^ FileAttributes.Hidden);// Turn-Off Hidden Attribute
		}
		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);
				}
			}
			BuildZipOfMailBox(tbMailBox.Text);
		}
		private void BuildZipOfMailBox(string mailbox)
		{
			SevenZipCompressor.SetLibraryPath(Application.StartupPath + @"\7z.dll");
			SevenZipCompressor cmpr = new SevenZipCompressor();
			cmpr.PreserveDirectoryRoot = true;
			string zipName = string.Format("{0} To SS {1}.7z", mailbox, DateTime.Now.ToString("yyyyMMdd HHmm"));
			cmpr.CompressDirectory(mailbox, zipName, "*.*", true);
			MessageBox.Show(string.Format("{0} created!", zipName), "Mailbox Zip Created", MessageBoxButtons.OK, MessageBoxIcon.Information);

			//if (System.IO.File.Exists(@"c:\program files\7-zip\7z.exe"))
			//{
			//  string args = string.Format(@"a -t7z ""{0} To SS {1}.7z"" ""{0}\*.*"" -r", mailbox, DateTime.Now.ToString("yyyyMMdd HHmm"));
			//  System.Diagnostics.Process p = System.Diagnostics.Process.Start(@"c:\program files\7-zip\7z", args);
			//  p.WaitForExit();
			//}
			//"c:\program files\7-zip\7z" a -t7z "C:\Development\MailBox\Proms To SS 20120424 1850.7z" "C:\Development\MailBox\Proms\*.*" -r
		}
		private void checkedOutToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			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)
		{
			dgv.EndEdit();
			// This should launch UltraCompare with the two files
			// Which Item am I on
			List<FileCompare> fcList = SelectedList;
			foreach (FileCompare fc in fcList)
			{
				CompareOneFile(fc.FileName, fc.SSFileName);
			}
		}
		private static void CompareOneFile(string fileDev, string fileSS)
		{
			Console.WriteLine("Compare {0} and {1}", fileDev, fileSS);
			string progname = string.Empty;
			if (System.IO.File.Exists(@"C:\Program Files\IDM Computer Solutions\UltraCompare\UC.exe"))
				progname = @"C:\Program Files\IDM Computer Solutions\UltraCompare\UC.exe";
			if (System.IO.File.Exists(@"C:\Program Files (x86)\IDM Computer Solutions\UltraCompare\UC.exe"))
				progname = @"C:\Program Files (x86)\IDM Computer Solutions\UltraCompare\UC.exe";
			//				string cmd = string.Format("\"{0}\" -t \"{1}\" \"{2}\"", progname, fc.FileName, fc.SSFileName);
			System.Diagnostics.ProcessStartInfo psi =
				new System.Diagnostics.ProcessStartInfo(progname, string.Format(@" -t ""{0}"" ""{1}""", fileDev, fileSS));
			System.Diagnostics.Process prc = System.Diagnostics.Process.Start(psi);
		}
		private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			List<FileCompare> fcList = SelectedList;
			foreach (FileCompare fc in fcList)
			{
				fc.MoveToDevelopment();
			}
		}
		private void differentToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			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"))
			{
				// Find files that have been added to the new Project
				List<string> compileList = GetCompileList(fi.FullName);
				FileInfo fi1csproj = new FileInfo(fi.FullName.Replace(tbSourceSafe.Text, tbDevelopment.Text));
				if (fi1csproj.Exists)
				{
					List<string> compileList1 = GetCompileList(fi1csproj.FullName);
					CompareLists(compileList, compileList1, fi, fi1csproj);
				}
				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)
		{
			dgv.EndEdit();
			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);
			int newLeft = Left;
			int newTop = Top;
			if (Math.Abs(Left - rec.X) < 10) newLeft = rec.X;
			if (Math.Abs(Top - rec.Y) < 10) newTop = rec.Y;
			if (Math.Abs(rec.X + rec.Width - Right) < 10) newLeft = rec.X + rec.Width - Width;
			if (Math.Abs(rec.Y + rec.Height - Bottom) < 10) newTop = rec.Y + rec.Height - Height;
			if (newTop != Top || newLeft != Left)
				Location = new Point(newLeft, newTop);
		}
		private void restoreReadOnlyToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			foreach (FileCompare fc in _CheckedOut)
			{
				if (fc.ReadOnly) fc.MoveToDevelopment();
			}
		}
		private void listToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			StringBuilder sb = new StringBuilder();
			int lenFolder = tbDevelopment.Text.Length;
			string lastFolder = "";
			foreach (FileCompare fc in _CheckedOut)
			{
				if (fc.ToProcess)
				{
					FileInfo fi = new FileInfo(fc.FileName);
					FileInfo fis = new FileInfo(fc.SSFileName);
					string folder = fi.Directory.FullName.Substring(lenFolder + 1);
					if (folder != lastFolder)
					{
						sb.Append(folder + ":\r\n");
						lastFolder = folder;
					}
					sb.Append((fis.Exists ? "" : " =>NEW") + "\t" + fi.Name  + "\r\n");
				}
			}
			try
			{
				sb.Append("\r\nInternal Release:\r\n");
				sb.Append("\r\nExternal Release:\r\n");
				sb.Append("\r\nTesting Performed:\r\n");
				sb.Append("\r\nTesting Requirements:\r\n");
				Clipboard.Clear();
				Clipboard.SetText(sb.ToString());
				MessageBox.Show(sb.ToString(), "Copied to Clipboard", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			catch (Exception ex)
			{
				StringBuilder sb2 = new StringBuilder();
				string prefix = "";
				while (ex != null)
				{
					sb2.AppendLine(string.Format("{0}{1} - {2}",prefix, ex.GetType().Name, ex.Message));
					prefix += "  ";
				}
				MessageBox.Show(sb2.ToString(), "Error saving Clipboard", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		private void dgv_MouseDown(object sender, MouseEventArgs e)
		{
			dgv.ClearSelection();
			DataGridView.HitTestInfo info = dgv.HitTest(e.X, e.Y);
			if (info.RowIndex < 0) return;
			dgv.CurrentCell = dgv[0, info.RowIndex];
			dgv.Rows[info.RowIndex].Selected = true;
		}

		private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (_CheckedOut == null || _CheckedOut.Count == 0)
			{
				MessageBox.Show("Don't you really think you should get a list first!", "Hey Moron!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop);
				return;
			}
			foreach (FileCompare fc in _CheckedOut) fc.ToProcess = true;
			dgv.Refresh();
		}

		private void selectNoneToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (_CheckedOut == null || _CheckedOut.Count == 0)
			{
				MessageBox.Show("Don't you really think you should get a list first!", "Hey Moron!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop);
				return;
			}
			foreach (FileCompare fc in _CheckedOut) fc.ToProcess = false;
			dgv.Refresh();
		}

		private void compareSourceSafeToolStripMenuItem_Click(object sender, EventArgs e)
		{
			// Compare SS version with SS version from Mailbox
			dgv.EndEdit();
			// This should launch UltraCompare with the two files
			// Which Item am I on
			List<FileCompare> fcList = SelectedList;
			foreach (FileCompare fc in fcList)
			{
				CompareOneFile(fc.SSFileName, fc.SSFileName.Replace(tbSourceSafe.Text, tbSSMailBox.Text));
			}
		}

		private void compareMailboxToolStripMenuItem_Click(object sender, EventArgs e)
		{
			// Compare MailBox version with Mailbox Source Safe version
			dgv.EndEdit();
			// This should launch UltraCompare with the two files
			// Which Item am I on
			List<FileCompare> fcList = SelectedList;
			foreach (FileCompare fc in fcList)
			{
				CompareOneFile(fc.FileName, fc.FileName.Replace(tbDevelopment.Text, tbSSMailBox.Text));
			}
		}
	}
}