
using System;
using System.Data;
using System.Collections.Generic;
using System.IO;
using Mono.Data.Sqlite;
using MonoTouch.UIKit;
using MonoTouch.Foundation;

namespace NavTestDB
{
	partial class RootViewController : UITableViewController
	{
		public RootViewController(IntPtr handle) : base(handle)
		{
		}
		
		SqliteConnection connection;
		string dbPath;
		List<Customer> customerList;

		public override void ViewDidLoad()
		{
			base.ViewDidLoad();
			
			//Create the DB and insert some rows
			var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
			dbPath = Path.Combine(documents, "NavTestDB.db3");
			var dbExists = File.Exists(dbPath);
			if (!dbExists)
				SqliteConnection.CreateFile(dbPath);
			connection = new SqliteConnection("Data Source=" + dbPath);
			try
			{
				connection.Open();
				using (SqliteCommand cmd = connection.CreateCommand())
				{
					cmd.CommandType = CommandType.Text;
					if (!dbExists)
					{
						const string TblColDefs = 
							" Customers (CustID INTEGER NOT NULL, FirstName ntext, LastName ntext, Town ntext)";
						const string TblCols = 
							" Customers (CustID, FirstName, LastName, Town) ";
						
						string[] statements = {
							"CREATE TABLE" + TblColDefs,
							"INSERT INTO" + TblCols + "VALUES (1, 'John', 'Smith', 'Manchester')",
							"INSERT INTO" + TblCols + "VALUES (2, 'John', 'Doe', 'Dorchester')",
							"INSERT INTO" + TblCols + "VALUES (3, 'Fred', 'Bloggs', 'Winchester')",
							"INSERT INTO" + TblCols + "VALUES (4, 'Walter P.', 'Jabsco', 'Ilchester')",
							"INSERT INTO" + TblCols + "VALUES (5, 'Jane', 'Smith', 'Silchester')",
							"INSERT INTO" + TblCols + "VALUES (6, 'Raymond', 'Luxury-Yacht', 'Colchester')" };
						foreach (string stmt in statements)
						{
							cmd.CommandText = stmt;
							cmd.ExecuteNonQuery();
						}
					}
					customerList = new List<Customer>();
					cmd.CommandText = "SELECT CustID, FirstName, LastName, Town FROM Customers ORDER BY LastName";
					using (SqliteDataReader reader = cmd.ExecuteReader())
					{
						while (reader.Read())
						{
							var cust = new Customer 
							{ 
								CustID = Convert.ToInt32(reader["CustID"]), 
								FirstName = reader["FirstName"].ToString(),
								LastName = reader["LastName"].ToString(),
								Town = reader["Town"].ToString()
							};
							customerList.Add(cust);
						}
					}
				}
			} catch (Exception)
			{
				connection.Close();
			}
			
			this.TableView.Source = new DataSource(this);
		}

		/*
		public override void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear (animated);
		}
		*/
		/*
		public override void ViewDidAppear (bool animated)
		{
			base.ViewDidAppear (animated);
		}
		*/
		/*
		public override void ViewWillDisappear (bool animated)
		{
			base.ViewWillDisappear (animated);
		}
		*/
		/*
		public override void ViewDidDisappear (bool animated)
		{
			base.ViewDidDisappear (animated);
		}
		*/

		/*
		// Override to allow orientations other than the default portrait orientation
		public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
		{
			//return true for supported orientations
			return (InterfaceOrientation == UIInterfaceOrientation.Portrait);
		}
		*/

		public override void DidReceiveMemoryWarning()
		{
			// Releases the view if it doesn't have a superview.
			base.DidReceiveMemoryWarning();
			
			// Release any cached data, images, etc that aren't in use.
		}

		public override void ViewDidUnload()
		{
			// Release anything that can be recreated in viewDidLoad or on demand.
			// e.g. this.myOutlet = null;
			
			//Delete the sample DB. Pointlessly kill table in the DB first.
			using (SqliteCommand cmd = connection.CreateCommand())
			{
				cmd.CommandText = "DROP TABLE IF EXISTS Customers";
				cmd.CommandType = CommandType.Text;
				connection.Open();
				cmd.ExecuteNonQuery();
				connection.Close();
			}
			File.Delete(dbPath);
			
			base.ViewDidUnload();
		}

		class DataSource : UITableViewSource
		{
			RootViewController controller;

			public DataSource(RootViewController controller)
			{
				this.controller = controller;
			}

			private void InfoAlert(string msg)
			{
				using (UIAlertView av = new UIAlertView("Info", msg, null, "OK", null))
				{
					av.Show();
				}
			}

			public override int NumberOfSections(UITableView tableView)
			{
				return 1;
			}

			// Customize the number of rows in the table view
			public override int RowsInSection(UITableView tableview, int section)
			{
				return controller.customerList.Count;
			}

			// Customize the appearance of table view cells.
			public override UITableViewCell GetCell(UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
			{
				string cellIdentifier = "Cell";
				var cell = tableView.DequeueReusableCell(cellIdentifier);
				if (cell == null)
				{
					cell = new UITableViewCell(UITableViewCellStyle.Subtitle, cellIdentifier);
					//Add in a detail disclosure icon to each cell
					cell.Accessory = UITableViewCellAccessory.DetailDisclosureButton;
				}
				
				// Configure the cell.
				var cust = controller.customerList[indexPath.Row];
				cell.TextLabel.Text = String.Format("{0} {1}", cust.FirstName, cust.LastName);
				cell.DetailTextLabel.Text = cust.Town;
				
				return cell;
			}

			public override void AccessoryButtonTapped(UITableView tableView, NSIndexPath indexPath)
			{
				var cust = controller.customerList[indexPath.Row];
				InfoAlert(string.Format("{0} {1} has ID {2}", cust.FirstName, cust.LastName, cust.CustID));
			}

			/*
			// Override to support conditional editing of the table view.
			public override bool CanEditRow (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
			{
				// Return false if you do not want the specified item to be editable.
				return true;
			}
			*/
			/*
			// Override to support editing the table view.
			public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, MonoTouch.Foundation.NSIndexPath indexPath)
			{
				if (editingStyle == UITableViewCellEditingStyle.Delete) {
					controller.TableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade);
				} else if (editingStyle == UITableViewCellEditingStyle.Insert) {
					// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
				}
			}
			*/
			/*
			// Override to support rearranging the table view.
			public override void MoveRow (UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath)
			{
			}
			*/
			/*
			// Override to support conditional rearranging of the table view.
			public override bool CanMoveRow (UITableView tableView, NSIndexPath indexPath)
			{
				// Return false if you do not want the item to be re-orderable.
				return true;
			}
			*/

			// Override to support row selection in the table view.
			public override void RowSelected(UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
			{
				// Navigation logic may go here -- for example, create and push another view controller.
				// var anotherViewController = new AnotherViewController ("AnotherView", null);
				//controller.NavigationController.PushViewController (anotherViewController, true);
			}
		}
	}
	
}

