using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using APE.model;

namespace APE.presentation {
	/// <summary>
	/// Height of the tab header should be 17 unipx. 17 unipx is the height of the draggable area.
	/// </summary>
	public partial class Tab : System.Windows.Controls.TabItem {

		string currentDirectory;
		FileStructure fs;

		public Tab(string dir) {
			currentDirectory = dir;
			fs = new FileStructure(currentDirectory);
			currentDirectory = fs.leaf.Name;

			InitializeComponent();
			initTabInterface();
			HeaderTemplate = (DataTemplate)Resources["Header"];
			Header = convertDirNameForHeader(currentDirectory);
		}

		#region Interface Initialization

		private void initTabInterface() {
			populateList();
			initBreadcrumb();
		}

		private void populateList() {
			fileList.Items.Clear();
			foreach (AbstractNode a in fs.leaf.children) {
				fileList.Items.Add(new ListItem(a, List.ViewingModes.Tiles));
			}
		}

		private void initBreadcrumb() {
		}

		public void refresh() {
			fs.refresh();
			populateList();
			currentDirectory = fs.leaf.Name;
			Header = convertDirNameForHeader(currentDirectory);
		}

		#endregion

		#region Event Handlers

		private void OnNodeSelected(object sender, RoutedEventArgs e) {
			var node = (e as ListItem.NodeSelectedEventArgs).selectedNode;
			fs.goDeeper(node);
			populateList();
			currentDirectory = node.Name;
			Header = convertDirNameForHeader(currentDirectory);
		}

		private void OnBack(object sender, RoutedEventArgs e) {
			fs.goBack();
			populateList();
			currentDirectory = fs.leaf.Name;
			Header = convertDirNameForHeader(currentDirectory);
		}

		private void OnPaste(object sender, RoutedEventArgs e) {
			(e as List.PasteEventArgs).DestinationNode = fs.leaf;
		}

		private void TextBlock_MouseEnter(object sender, MouseEventArgs e) {
			var textBlock = sender as TextBlock;
			this.IsSelected = true;
		}

		#endregion

		#region Utilities

		private string convertDirNameForHeader(string dir) {
			if (dir == "Root") {
				return "Computer";
			} else if (dir.Length > 25) {
				return dir.Substring(0, 27) + "...";
			}
			return dir;
		}

		#endregion
	}
}
