unit productsgrid;
// opcenito za prikaz i editiranje productsa od developera
interface

uses SysUtils, AppTypesDB, productsDB, System.Data, System.Web.UI, StrUtils, System.Drawing, System.Web.UI.WebControls;

const
	//na kojem indexu u e.Item.Controls[?] as TableCell
	ProductIDCI=0;
	TemplateCI=1;
	DescriptionCI=2;
	SearchWordsCI=3;
	EditCI=4;

type TProductsGrid = Class(System.Web.UI.WebControls.DataGrid)
	private
		fErrorLabel : System.Web.UI.WebControls.Label;
		fRows:integer;
		fDeveloperID : integer; 
		fDeveloperName : string;
		procedure SetDeveloperID(Value:integer);
		procedure SetRows(Value:integer);
		procedure SetDeveloperName(Value:string);
	public
		constructor Create;
  	procedure DoDataBind;
  strict protected
    procedure OnInit(E : EventArgs); override;
    procedure OnLoad(E : EventArgs); override;
		procedure OnEditCommand(E: DataGridCommandEventArgs); override;
		procedure OnCancelCommand(E: DataGridCommandEventArgs); override;
		procedure OnUpdateCommand(E: DataGridCommandEventArgs); override;
    procedure OnPageIndexChanged(E : DataGridPageChangedEventArgs); override;
    procedure OnItemCreated(E: DataGridItemEventArgs); override;
		procedure OnItemCommand(E: DataGridCommandEventArgs); override;
		procedure OnPreRender(E : EventArgs); override;
	published
		property DeveloperID : integer read fDeveloperID write SetDeveloperID;
		property Rows : integer read fRows write SetRows;
		property DeveloperName : string read fDeveloperName write SetDeveloperName;

		property ErrorLabel : System.Web.UI.WebControls.Label read fErrorLabel write fErrorLabel;
end;

implementation

procedure TProductsGrid.SetDeveloperName(Value:string);
begin
	if Value <> fDeveloperName then fDeveloperName := Value;
end;

procedure TProductsGrid.SetDeveloperID(Value:integer);
begin
	if Value <> fDeveloperID then fDeveloperID:=Value;
end;

procedure TProductsGrid.SetRows(Value:integer);
begin
	if Value <> fRows then fRows:=Value;
end;

procedure TProductsGrid.DoDataBind;
var
	product : TproductsDB;
begin
	product:=TproductsDB.Create;
//	ErrorLabel.Text:=inttostr(DeveloperID);
	DataSource := product.GetProductsByDeveloper(DeveloperID);
	Rows := (DataSource as DataTable).Rows.Count;
	
	if (CurrentPageIndex >= Rows / PageSize) then CurrentPageIndex:=0;
	
	DataBind;
end;


type
  TItemTemplate = Class(System.Object,ITemplate)
     procedure InstantiateIn(container:System.Web.UI.Control);
     procedure DoDataBinding(Sender: System.Object; E: System.EventArgs);
end;

procedure TItemTemplate.DoDataBinding(Sender: System.Object; E:System.EventArgs);
var
	  sImg:string;
	 
    aHL : System.Web.UI.WebControls.PlaceHolder;

    lNaziv:System.Web.UI.WebControls.HyperLink;
    lDeveloper:System.Web.UI.WebControls.Label;
    lDescription:System.Web.UI.WebControls.Label;
    slika:System.Web.UI.WebControls.Image;
		 lHits:System.Web.UI.WebControls.Literal;

    Container: System.Web.UI.WebControls.DataGridItem;
begin
    aHL:=(Sender as System.Web.UI.WebControls.PlaceHolder);
    Container := (aHL.NamingContainer as System.Web.UI.WebControls.DataGridItem);

    lNaziv:=HyperLink.Create;
    lNaziv.Text := '<b>' + DataBinder.Eval((Container as DataGridItem).DataItem, 'ProductName').ToString + '</b>';
    lNaziv.NavigateUrl:='webform1.aspx?id=' + DataBinder.Eval((Container as DataGridItem).DataItem, 'productid').ToString;
    lNaziv.CssClass:='oprgsmall';

    aHL.Controls.Add(lNaziv);

    lDeveloper:=System.Web.UI.WebControls.Label.Create;
    lDeveloper.Text := '<br>' +  DataBinder.Eval((Container as DataGridItem).DataItem, 'AppType').ToString;
    lDeveloper.CssClass:='oprgsmall';

    aHL.Controls.Add(lDeveloper);

    lDescription:=System.Web.UI.WebControls.Label.Create;
    lDescription.Text := '<br>' + DataBinder.Eval((Container as DataGridItem).DataItem, 'AppPayType').ToString;
    lDescription.CssClass:='oprgsmall';

    aHL.Controls.Add(lDescription);

		sImg := DataBinder.Eval((Container as DataGridItem).DataItem, 'ImageName').ToString;
		if sImg <> '' then
		begin
			slika:=System.Web.UI.WebControls.Image.Create;
			slika.ImageURl:=sImg;
			slika.Width:=System.Web.UI.WebControls.Unit.Pixel(80);
			slika.Height:=System.Web.UI.WebControls.Unit.Pixel(60);
			aHL.Controls.Add(LiteralControl.Create('<br>'));
			aHL.Controls.Add(slika);
		end;
		
		lHits:=Literal.Create;
		lHits.Text:='<br><i>Hits: ' + DataBinder.Eval((Container as DataGridItem).DataItem, 'nra').ToString + '</i>';
   aHL.Controls.Add(lHits);
		
end;


procedure TItemTemplate.InstantiateIn(container:System.Web.UI.Control);
 var
    aHL : System.Web.UI.WebControls.PlaceHolder;
begin
 aHL := System.Web.UI.WebControls.PlaceHolder.Create;
 aHL.add_DataBinding(DoDataBinding);
 container.Controls.Add(aHL);
end;

type
  TEditItemTemplate = Class(System.Object,ITemplate)
     procedure InstantiateIn(container:System.Web.UI.Control);
     procedure DoDataBinding(Sender: System.Object; E: System.EventArgs);
end;

procedure TEditItemTemplate.InstantiateIn(container:System.Web.UI.Control);
var
  aHL : System.Web.UI.WebControls.PlaceHolder;
	ProductNameValidator:System.Web.UI.WebControls.RequiredFieldValidator;
  txtProductName:System.Web.UI.WebControls.TextBox;
  cboAppType:System.Web.UI.WebControls.ListBox;
  cboAppPayType:System.Web.UI.WebControls.ListBox;
	apptypes : TAppTypesDB;
begin
	aHL := System.Web.UI.WebControls.PlaceHolder.Create;

	
  txtProductName:=System.Web.UI.WebControls.TextBox.Create;
  txtProductName.CssClass:='EditTextBox';
	txtProductName.Columns:=15;
	txtProductName.ID:='txtProductName';

	ProductNameValidator:=System.Web.UI.WebControls.RequiredFieldValidator.Create;
	ProductNameValidator.ID:='ProductNameValidator';
	ProductNameValidator.ControlToValidate := txtProductName.ClientID;
	ProductNameValidator.Display := ValidatorDisplay.Static;
	ProductNameValidator.EnableClientScript := true;
	ProductNameValidator.CssClass:='ErrorText';
	ProductNameValidator.Font.Size:=FontUnit.XXSmall;
	ProductNameValidator.ErrorMessage :='Name must not be left blank.';


  cboAppType:=System.Web.UI.WebControls.ListBox.Create;
	cboAppType.Rows:=1;
  cboAppType.CssClass:='EditTextBox';
					apptypes := TAppTypesDB.Create;
					cboAppType.DataSource:=apptypes.GetALLProductCategories;
					cboAppType.DataTextField:='name';
					cboAppType.DataValueField:='name';
					//cboAppType.DataBind; -> poziva se automatski kad se dogodi parentov-gridov bind
					//cboAppType.DataSource:=nil;

  cboAppPayType:=System.Web.UI.WebControls.ListBox.Create;
	cboAppPayType.Rows:=1;
  cboAppPayType.CssClass := 'EditTextBox';
					cboAppPayType.DataSource:=apptypes.GetAppPayTypes;
					cboAppPayType.DataTextField:='name';
					cboAppPayType.DataValueField:='name';
					//cboAppPayType.DataBind;
					//cboAppPayType.DataSource:=nil;

  aHL.Controls.Add(txtProductName);
  aHL.Controls.Add(cboAppType);
  aHL.Controls.Add(cboAppPayType);
	aHL.Controls.Add(ProductNameValidator);

	aHL.add_DataBinding(DoDataBinding);

	container.Controls.Add(aHL);
end;

procedure TEditItemTemplate.DoDataBinding(Sender: System.Object; E:System.EventArgs);
var
  Container: System.Web.UI.WebControls.DataGridItem;
  aHL : System.Web.UI.WebControls.PlaceHolder;
  txtProductName:System.Web.UI.WebControls.TextBox;
  cboAppType:System.Web.UI.WebControls.ListBox;
  cboAppPayType:System.Web.UI.WebControls.ListBox;
	i:integer;
	curValue:string;
begin
    aHL:=(Sender as System.Web.UI.WebControls.PlaceHolder);
    Container := (aHL.NamingContainer as System.Web.UI.WebControls.DataGridItem);

		//Controls[3] is field validator(last)!
		
    txtProductName:=TextBox.Create;
		txtProductName:=(aHL.Controls[0] as TextBox);
    txtProductName.Text := DataBinder.Eval((Container as DataGridItem).DataItem, 'ProductName').ToString;

    cboAppType:=System.Web.UI.WebControls.ListBox.Create;
		cboAppType:=(aHL.Controls[1] as ListBox);
		curValue := DataBinder.Eval((Container as DataGridItem).DataItem, 'AppType').ToString;
		for i:=0 to cboAppType.Items.Count-1 do
		begin
			if curValue = cboAppType.Items[i].Text then 
			begin
				cboAppType.SelectedIndex :=i ;
				Continue;
			end;
		end;

    cboAppPayType:=System.Web.UI.WebControls.ListBox.Create;
		cboAppPayType:=(aHL.Controls[2] as ListBox);
		curValue:=DataBinder.Eval((Container as DataGridItem).DataItem, 'AppPayType').ToString;
		for i:=0 to cboAppPayType.Items.Count-1 do
		begin
			if curValue = cboAppPayType.Items[i].Text then 
			begin
				cboAppPayType.SelectedIndex := i;
				Continue;
			end;
		end;
end;

procedure TProductsGrid.OnPageIndexChanged(E : DataGridPageChangedEventArgs);
begin
		inherited OnPageIndexChanged(E);

		EditItemIndex:=-1;
		SelectedIndex:=-1;
		CurrentPageIndex := e.NewPageIndex;
		try
			DoDataBind;
		except
			on E : Exception do
				ErrorLabel.Text:='Error: ' + E.Message;
		end;
end;

procedure TProductsGrid.OnItemCreated(E : DataGridItemEventArgs);
var
   itemType : ListItemType;
   polje : TableCell;
   lit : LiteralControl;
		DelBtn : LinkButton;
		txtDescription:TextBox;
		ZapisOD, ZapisDO : integer;
begin
	inherited OnItemCreated(E);
	try
    itemType := e.Item.ItemType;
    If (itemType = ListItemType.Pager) Then
    begin//editiraj pager
		 	 ZapisOD := 1 + CurrentPageIndex * PageSize;
			 ZapisDO := PageSize + CurrentPageIndex * PageSize;
			 if ZapisDO > Rows then ZapisDO:=Rows;  
      lit:=LiteralControl.Create;
      lit.Text:='Found ' + IntToStr(Rows) + ' records. Displaying ' + IntToStr(ZapisOD) + ' / ' + IntToStr(ZapisDO) + '.';
      lit.Text:= lit.Text + ' Goto page: ';
      //lit.ID:='CatPagerDescription';
      polje := (e.Item.Controls[0] as TableCell);
      polje.Controls.AddAt(0,lit);
			lit.Free;
    end;
    If (itemType = ListItemType.Item) OR (itemType = ListItemType.AlternatingItem) OR (itemType = ListItemType.SelectedItem) Then
    begin//dodaj delete button
			 //skrati desc polje
			 (e.Item.Controls[DescriptionCI] as TableCell).Text := LeftStr((e.Item.Controls[DescriptionCI] as TableCell).Text, 150) + '...';
			 
       polje := (e.Item.Controls[EditCI] as TableCell);

			 lit:=LiteralControl.Create;
			 lit.Text:='<br><br>';
			 polje.Controls.Add(lit);

			 DelBtn:=LinkButton.Create;
			 DelBtn.CausesValidation := false;
			 DelBtn.CommandName:='DELETE';
			 DelBtn.Attributes.Add('onclick','return confirm(''Delete this entry?'')');
			 DelBtn.Text:='Delete';
			 polje.Controls.Add(DelBtn)
		end;
    If (itemType = ListItemType.EditItem) Then
    begin 
			begin //description text max i vise redova
       	polje := (e.Item.Controls[DescriptionCI] as TableCell);
				txtDescription:=(polje.Controls[0] as TextBox);
				txtDescription.TextMode:=TextBoxMode.MultiLine;
				txtDescription.Rows:=7;
				txtDescription.cssClass:='EditTextBox';
			end;
			begin //searchwords text max i vise redova
       	polje := (e.Item.Controls[SearchWordsCI] as TableCell);
				txtDescription:=(polje.Controls[0] as TextBox);
				txtDescription.TextMode:=TextBoxMode.MultiLine;
				txtDescription.Rows:=7;
				txtDescription.cssClass:='EditTextBox';
			end;
			begin// razmkni update i cancel buttone	
       	polje := (e.Item.Controls[EditCI] as TableCell);
				(polje.Controls[0] as LinkButton).CausesValidation:=true; //update
				(polje.Controls[2] as LinkButton).CausesValidation:=false; //cancel
				try
			 		lit:=(polje.Controls[1] as LiteralControl);
			 		lit.Text:='<br><br>';
				except
			 		lit:=LiteralControl.Create;
			 		lit.Text:='<br><br>';
			  	polje.Controls.AddAt(1,lit);
				end;
			end;
		end;
	finally
	end;
end;

procedure TProductsGrid.OnItemCommand(E: DataGridCommandEventArgs);
var
	products:TproductsDB;
	ProductID:integer;
begin
	Rows:=1;
	inherited OnItemCommand(E);
	if E.CommandName='DELETE' then
	begin
		SelectedIndex:=E.Item.ItemIndex;
		ProductID:=StrToInt(SelectedItem.Cells[0].Text);
		products:=TproductsDB.Create;
		try
			products.DeleteProduct(ProductID);
			DoDataBind;//ovo mjeja Rows
			SelectedIndex := -1;
		except
			on E : Exception do
				ErrorLabel.Text:='Error: ' + E.Message;
		end;
		products.Free;
	end;
end;

procedure TProductsGrid.OnEditCommand(E: DataGridCommandEventArgs);
begin
		//inherited OnEditCommand(E);
		SelectedIndex:=E.Item.ItemIndex;
		EditItemIndex:=E.Item.ItemIndex;
		
//		ErrorLabel.Text:=inttostr(EditItemIndex);
		
		try
			DoDataBind;
		except
			on E : Exception do
				ErrorLabel.Text:='Error: ' + E.Message;
		end;
end;

procedure TProductsGrid.OnCancelCommand(E: DataGridCommandEventArgs);
begin
		inherited OnCancelCommand(E);
		//SelectedIndex:=-1;
		EditItemIndex:=-1;
		try
			DoDataBind;
		except
			on E : Exception do
				ErrorLabel.Text:='Error: ' + E.Message;
		end;
end;

procedure TProductsGrid.OnUpdateCommand(E: DataGridCommandEventArgs);
var
	products:TproductsDB;
	ProductID:integer;
	aHL : System.Web.UI.WebControls.PlaceHolder;
	ProductName, AppType, AppPayType, Description, SearchWords :string;
begin
	inherited OnUpdateCommand(E);

	aHL := System.Web.UI.WebControls.PlaceHolder.Create;
	aHL := (SelectedItem.Cells[TemplateCI].Controls[0] as PlaceHolder);
//	if not (aHL.Controls[aHL.Controls.Count-1] as RequiredFieldValidator).IsValid then Exit;
	ProductID := StrToInt(SelectedItem.Cells[ProductIDCI].Text);
//  first control[0] is a placeholder!!
	ProductName := (SelectedItem.Cells[TemplateCI].Controls[0].Controls[0] as TextBox).Text;
	AppType := (SelectedItem.Cells[TemplateCI].Controls[0].Controls[1] as ListBox).SelectedItem.Text;
	AppPayType := (SelectedItem.Cells[TemplateCI].Controls[0].Controls[2] as ListBox).SelectedItem.Text;
	Description := (SelectedItem.Cells[DescriptionCI].Controls[0] as TextBox).Text;
	SearchWords := (SelectedItem.Cells[SearchWordsCI].Controls[0] as TextBox).Text;


	
	products:=TproductsDB.Create;
	try
		products.UpdateProduct(ProductID, DeveloperName, ProductName, AppType, AppPayType, Description, SearchWords);
		EditItemIndex:=-1;
		DoDataBind;
	except
			on E : Exception do
				ErrorLabel.Text:='Error: ' + E.Message;
	end;
	products.Free;
end;

constructor TProductsGrid.Create;
begin

    inherited create;

		fErrorLabel := System.Web.UI.WebControls.Label.Create;
		
		ItemStyle.BackColor:=Color.White;
		AlternatingItemStyle.BackColor:=Color.GhostWhite;
		SelectedItemStyle.BackColor:=Color.CornflowerBlue;
		
    AutoGenerateColumns := False;
    ShowFooter := False;
    //ShowHeader := False;
    Width := System.Web.UI.WebControls.Unit.Percentage(100);
    BorderWidth := System.Web.UI.WebControls.Unit.Pixel(1);
		BorderColor:=Color.CornflowerBlue;
    GridLines := System.Web.UI.WebControls.GridLines.Horizontal;
		CellPadding:=2;
		
		HeaderStyle.Font.Bold:=true;
		HeaderStyle.ForeColor:=Color.White;
		HeaderStyle.BackColor:=Color.DarkBlue;
		HeaderStyle.BorderStyle:=System.Web.UI.WebControls.BorderStyle.Solid;
    
    AllowPaging := True;
    PageSize:=6;

    PagerStyle.Mode := PagerMode.NumericPages;
		//PagerStyle.NextPageText := 'Next »';
		//PagerStyle.PrevPageText := '« Previous';
    PagerStyle.PageButtonCount := 5;
    PagerStyle.HorizontalAlign := System.Web.UI.WebControls.HorizontalAlign.Left;
    PagerStyle.Position:=PagerPosition.Top;
    PagerStyle.cssClass:='CatPager';

end;

procedure TProductsGrid.OnLoad(E : EventArgs);
begin
//	if not Page.IsPostBack then DoDataBind;
	inherited OnLoad(E);
end;

procedure TProductsGrid.OnInit(E : EventArgs);
var
  dgColumn : TemplateColumn;
	EditColumn : EditCommandColumn;
	//DeleteColumn : EditCommandColumn;
	ProdIDColumn, DescriptionColumn, SearchWordsColumn : BoundColumn;
begin
		inherited OnInit(E);

		ProdIDColumn := BoundColumn.Create;
		with ProdIDColumn do
		begin
			Visible:=false;//Style.Add('display','none');
			ReadOnly := true;
			DataField := 'ProductID';
			CssClass := 'oprgsmall';
  		ItemStyle.VerticalAlign := VerticalAlign.Top;
		end;
    Columns.Add(ProdIDColumn);

    dgColumn := TemplateColumn.Create;
    with dgColumn do
    begin
        Initialize;
        ItemTemplate := TItemTemplate.create;
        EditItemTemplate := TEditItemTemplate.create;
				ItemStyle.VerticalAlign := VerticalAlign.Top;
				ItemStyle.Width:=System.Web.UI.WebControls.Unit.Pixel(150);
				HeaderText:='Example';
    end;
    Columns.Add(dgColumn);

		DescriptionColumn := BoundColumn.Create;
		with DescriptionColumn do
		begin
			DataField:='Description';
			CssClass:='oprgsmall';
  		ItemStyle.VerticalAlign := VerticalAlign.Top;
			HeaderText:='Description';
		end;
    Columns.Add(DescriptionColumn);

		SearchWordsColumn := BoundColumn.Create;
		with SearchWordsColumn do
		begin
			DataField:='SearchWords';
			CssClass:='oprgsmall';
  		ItemStyle.VerticalAlign := VerticalAlign.Top;
			ItemStyle.Width:=System.Web.UI.WebControls.Unit.Pixel(80);
			EditItemStyle.Width:=System.Web.UI.WebControls.Unit.Pixel(80);
			HeaderText:='Search keywords';
		end;
    Columns.Add(SearchWordsColumn);

		EditColumn := EditCommandColumn.Create;
		with EditColumn do
		begin
			//Width:=System.Web.UI.WebControls.Unit.Pixel(50);
			ButtonType:=ButtonColumnType.LinkButton;
			CancelText:='Cancel';
			EditText := 'Edit';
			UpdateText := 'Save';
  		ItemStyle.VerticalAlign := VerticalAlign.Top;
			ItemStyle.Width:=System.Web.UI.WebControls.Unit.Pixel(60);
//			ItemStyle.BackColor:=Color.CornflowerBlue;
			EditItemStyle.Width:=System.Web.UI.WebControls.Unit.Pixel(60);
		end;
    Columns.Add(EditColumn);
end; //MYInti;

procedure TProductsGrid.OnPreRender(E : EventArgs);
var
	DisableEditOptionsScript : string;
begin
	inherited OnPreRender(E);

	if EditItemIndex <> -1 then
	begin
    //ako sam u edit modu disabliraj tri optiona i upisi dummy text u ProductName
		//na djelu za unosnovog jer kod editiranja u gridu ako je productname prazan
		//requiredfield validation ne pusta posto je "novi" naziv takodjer prazan
    	DisableEditOptionsScript:='<script language="JavaScript" type="text/javascript">' + #13#10;
			DisableEditOptionsScript:=DisableEditOptionsScript + '<!--' + #13#10;
			DisableEditOptionsScript:=DisableEditOptionsScript + 'document.all.EditOptions.style.display="none";' + #13#10;
			DisableEditOptionsScript:=DisableEditOptionsScript + 'document.all.oweEdit_txtProductName.value="dummy"' + #13#10;
			DisableEditOptionsScript:=DisableEditOptionsScript + '//-->' + #13#10;
			DisableEditOptionsScript:=DisableEditOptionsScript + '</script>';
			if (not Page.IsStartupScriptRegistered('DisableEditOptionsScript')) Then
      	Page.RegisterStartupScript('DisableEditOptionsScript', DisableEditOptionsScript);
	end
	else
	begin
    	DisableEditOptionsScript:='<script language="JavaScript" type="text/javascript">' + #13#10;
			DisableEditOptionsScript:=DisableEditOptionsScript + '<!--' + #13#10;
			DisableEditOptionsScript:=DisableEditOptionsScript + 'document.all.oweEdit_txtProductName.value=""' + #13#10;
			DisableEditOptionsScript:=DisableEditOptionsScript + '//-->' + #13#10;
			DisableEditOptionsScript:=DisableEditOptionsScript + '</script>';
			if (not Page.IsStartupScriptRegistered('DisableEditOptionsScript')) Then
      	Page.RegisterStartupScript('DisableEditOptionsScript', DisableEditOptionsScript);
	end;
end;

end.
