// JScript source code

import System;
import System.Collections;
import System.Collections.Specialized;
import System.Diagnostics;
import System.Data;
import System.Data.OleDb;
import System.Web.UI;
import System.Web.UI.WebControls;
import System.Web.UI.HtmlControls;
import System.Text;


public class SortTable extends Hashtable implements IComparable {
    public var sortField:String;

    public function SortTable() {
        this(null);
    }
    public function SortTable(sField:String) {
        sortField = sField;
    }

    public function IComparable.CompareTo(b:Object) : Int32 {
        if ( sortField == null ) {
            return 0;
        }

        return (this[sortField].CompareTo(SortTable(b)[sortField]));
    }
}


public class tableDetails extends ArrayList {
	function tableDetails(tbl:DataTable) {
		var column : DataColumn;
		for(column in tbl.Columns) {
			var detailsTable:SortTable = new SortTable("name");
			detailsTable["name"]=column.ColumnName;
			detailsTable["type"]=column.DataType.ToString();
			detailsTable["isPK"]=column.ColumnName.EndsWith("ID");
			detailsTable["ordinal"]=column.Ordinal;
			this.Add(detailsTable);
		}
	}
}
		

class dbx extends Page {

	var tableList : DataGrid =new DataGrid();
	var tableData : DataGrid =new DataGrid();
	var tableSchema : DataList = new DataList();
	var selectedTable : String;
	var tableInfo : tableDetails;

    function dbx() {
		Page.add_Load(PageLoad); 
	}


	

	function PageLoad(o:Object, sender:EventArgs) {
		if(Session["dbName"]=="none$selected")
			Response.Redirect("default2.aspx");
		openDatabase();
		establishTableView();
		this.tableList.DataSource=tableView;
		this.tableList.DataBind();
        if (Request.QueryString["tableName"] == null) {
            selectedTable = tableView.Table.Rows[0].Item(2);
		}
        else
            selectedTable = Request.QueryString["tableName"];
        tableColumns(selectedTable);
        if(Request.QueryString["getData"] != null)
			sampleData(selectedTable);
	}

	function get currentDatabase() : OleDbConnection {
		return OleDbConnection(Session["dbConnection"]);
	}

	function get tableView() : DataView {
		return DataView(Session["dbTables"]);
	}

	function establishTableView() : void {
		Session["dbTables"]=null;
		var schemaTable: DataTable;
		var myConnection : OleDbConnection = currentDatabase;
		schemaTable = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null );
		var tablesView : DataView = new DataView(schemaTable);
		tablesView.RowFilter="table_name not like \'MSys%\'";
		Session["dbTables"] = tablesView;
	}
	
	function openDatabase() {
		var dbName:String;
		dbName=Session["dbName"];
		Session["dbConnection"]=null;
		var m_cmd : OleDbCommand;
		var m_ds : DataSet;		
		var m_conn : OleDbConnection;
		var m_connectionString : String;
		m_connectionString=new String("Provider=Microsoft.JET.OLEDB.4.0;data source=\\JSNetProgramming\\data\\"+dbName);
		m_conn = new OleDbConnection (m_connectionString);
		m_conn.Open();
		
		Session["dbConnection"]=m_conn;
	}
	
	function tableColumns (tableName:String) : DataView {

		var schemaTable: DataTable;
		var myConnection : OleDbConnection = currentDatabase;
		schemaTable = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, null );
		var tablesView : DataView = new DataView(schemaTable);
		tablesView.RowFilter="table_name=\'" + tableName + "\'";
		tableSchema.DataSource=tablesView;
		tableSchema.DataBind();
		return tablesView;
	}		


	function sampleData (tableName:String) : DataSet {
		
		var cmd : OleDbCommand = new OleDbCommand();
		cmd.Connection = this.currentDatabase;
		var ds : DataSet=new DataSet();
		var dataAdapter : OleDbDataAdapter;
		cmd.CommandText="select  top 5 * from [" + tableName + "]";
		dataAdapter= new OleDbDataAdapter();
		dataAdapter.SelectCommand =cmd;
		dataAdapter.Fill(ds);
		//note..
		var  dsv :DataView= new DataView(ds.Tables[0]);
		//
		
		var dt : DataTable = ds.Tables[0];
		tableInfo=new tableDetails(ds.Tables[0]);
		
		// this should not be here...
		tableData.DataSource=dsv;
		
		
		tableData.DataBind();
		
		// this is okay...
		return ds;
	}		
	
    public function OnCancelCommandTitlesGrid( sender:Object,  e:DataGridCommandEventArgs) {
		var bcc : DataGridColumn;
		var dcc : DataGridColumnCollection = tableData.Columns;

		Trace.Write("OnCancelCommandTitlesGrid");
		if(bcc instanceof DataGridColumn)
			Trace.Write("instanceof DataGridColumn");
		
		if(bcc instanceof BoundColumn)
			Trace.Write("instanceof BoundColumn");
		
		if(bcc instanceof ButtonColumn)
			Trace.Write("instanceof ButtonColumn");
		
		if(bcc instanceof EditCommandColumn)
			Trace.Write("instanceof EditCommandColumn");
		
		if(bcc instanceof HyperLinkColumn)
			Trace.Write("instanceof HyperLinkColumn");
			
		if(bcc instanceof TemplateColumn)
			Trace.Write("instanceof TemplateColumn");

        tableData.EditItemIndex = -1;
        sampleData(selectedTable);
    }

    // Handles the EditCommand event in the titles grid to beging editing
    // of a row
    public function OnEditCommandTitlesGrid( sender:Object, e:DataGridCommandEventArgs ) {
		var bcc : DataGridColumn;
		var dcc : DataGridColumnCollection = tableData.Columns;

		

		Trace.Write("OnEditCommandTitlesGrid");
        tableData.EditItemIndex = e.Item.ItemIndex;
        sampleData(selectedTable);
    }

    public function OnUpdateCommandTitlesGrid( sender:Object, e:DataGridCommandEventArgs ) {
    		var bcc : DataGridColumn;
		//var dcc : DataGridColumnCollection = tableData.Columns;


		Trace.Write("OnUpdateCommandTitlesGrid");
		var dgi : DataGridItem = e.Item; //tableData.Items[e.Item.ItemIndex];
		
		
		
		var dtc : TableCell;
		var ctr : int;
		var txtbox : TextBox;
		ctr=0;
		for(dtc in dgi.Cells){
			Trace.Write(dtc);
			Trace.Write(dtc.Text);
			if(e.Item.Cells[ctr].Controls[0] instanceof TextBox) {
				txtbox = TextBox(e.Item.Cells[ctr].Controls[0]);
				Trace.Write(dtc + " = " + txtbox.Text + " at " + ctr);
			}
			else
				Trace.Write("Not an instance of TextBox");
			ctr++;
		}
		


		
		//((-1*(tableInfo[0]["ordinal"]+1))+e.Item.Cells.Count)
        Trace.Write("Looking for " + tableInfo[0]["name"] + " at position " + tableInfo[0]["ordinal"] );
         var priceText:TextBox = TextBox(e.Item.FindControl("ctrl2:ctrl3"));
         //prev:var priceText:TextBox = TextBox(e.Item.Cells[(tableInfo[0]["ordinal"]+1)].Controls[0]);
         //var priceText:Control = e.Item.FindControl("OrderID");
         //Trace.Write("cast control[0] to a TextBox...");
         //txtbox = TextBox(priceText.Controls[0]);
         //if(txtbox==null) Trace.Write("NULL");
         Trace.Write("extract text value...");
         var newPrice:String = priceText.Text;
         Trace.Write("The value is " + newPrice);

		var cmd : OleDbCommand = new OleDbCommand();
		cmd.Connection = this.currentDatabase;
		var ds : DataSet=new DataSet();
		//var dataAdapter : OleDbDataAdapter;
		//cmd.CommandText="select * from [" + selectedTable + "] where ["+tableInfo[0]["name"]+"] = " + priceText.Text;
		//Trace.Write(cmd.CommandText);
		//dataAdapter= new OleDbDataAdapter();
		//dataAdapter.SelectCommand =cmd;
		//dataAdapter.Fill(ds);

        //var dtt: DataTable = ds.Tables[0];
        //var drr : DataRow[] = dtt.Select("["+tableInfo[0]["name"]+"]=" + priceText.Text);
        //var dre : DataRow = drr[0];
        
        //var dr:DataRow = ds.Tables[0].Rows[0];
        //var dcc : DataColumn;
        //var j : int;
        //for(j=0;j<dr.ItemArray.Length;j++)
		//	Trace.Write("Row["+j+"] = "+dr[j]);
		
		var nvc:NameValueCollection=Request.Form;
		//del:String[] arr1 = coll.AllKeys; // Get names of all forms into a string array.
		

		var sb : StringBuilder=new StringBuilder("update [");
		var fn: int;
		var addStringValue,textBoxValue:String;
		var addQuote : Boolean;
		fn=0;
		sb.Append(selectedTable);
		sb.Append("] set ");
		for(fn=0;fn<tableInfo.Count;fn++) {
			if(tableInfo[fn]["isPK"]) continue;
			sb.Append("[");
			sb.Append(tableInfo[fn]["name"]);
			sb.Append("]");
			sb.Append(" = ");
			addQuote=Boolean(tableInfo[fn]["type"]=="System.String" || tableInfo[fn]["type"]=="System.DateTime")
			textBoxValue=nvc.Item(fn+1);
			//prev:textBoxValue=TextBox(e.Item.Cells[(tableInfo[fn]["ordinal"]+1)].Controls[0]).Text;


			//if(addQuote && textBoxValue=="") 
			//	sb.Append("null");
			//else {
				
				if(textBoxValue=="") {
					 addStringValue="null";
					 sb.Append(addStringValue);
				}
				else
				{
					if(addQuote)
						sb.Append("'");
					addStringValue=textBoxValue.Replace("'","''");
					sb.Append(addStringValue);
					if(addQuote)
						sb.Append("'");
				}
			//}
			
			if(fn<=tableInfo.Count-2)
				sb.Append(",");
		}
		sb.Append(" WHERE ");
		sb.Append("[");
		sb.Append(tableInfo[0]["name"]);
		sb.Append("] = ");
		addQuote=Boolean(tableInfo[0]["type"]=="System.String" || tableInfo[0]["type"]=="System.DateTime")		
		if(addQuote)
			sb.Append("'");
		textBoxValue=TextBox(e.Item.Cells[(tableInfo[0]["ordinal"]+1)].Controls[0]).Text;
		sb.Append(textBoxValue);
		if(addQuote)
			sb.Append("'");
		sb.Append(";");
		Trace.Write(sb);		
		cmd.CommandText=sb;
		cmd.ExecuteNonQuery();

        tableData.EditItemIndex = -1;
        sampleData(selectedTable);
    }

	
}