using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UMinho.GestaoProjectos.DataAccess;
using Telerik.Web.UI;
using System.Data.Metadata.Edm;
using System.Text;
using UMinho.GestaoProjectos.Config;
using System.IO.Compression;
using System.IO;
using UMinho.GestaoProjectos.Exceptions;
using UMinho.Framework.Web.UI;
using UMinho.Framework.DataAccess;
using System.Data;
using System.Data.Linq;
using System.Data.SqlClient;
using System.Configuration;

using System.Collections;
using System.Diagnostics;
using System.Data.Common;
using UMinho.GestaoProjectos.BLL;

using UMinho.Framework.Common;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


namespace UMinho.GestaoProjectos.Views
{
    public partial class ViewEmissaoTimeSheet : UMinho.Framework.Web.UI.BaseView
    {

        #region Forms reuse
        public Utils.FormMode FormMode
        {
            get { return ViewState["___formmode"] == null ? Utils.FormMode.CreateMode : (Utils.FormMode)ViewState["___formmode"]; }

            set { ViewState["___formmode"] = value; }
        }
        //ID
        public int ID
        {
            get { return ViewState["___entitypk"] == null ? 0 : (int)ViewState["___entitypk"]; }

            set { ViewState["___entitypk"] = value; }
        }
        #endregion

        //Aceder ás BLL's
        BLLListagemTimesheets listagembll = new BLLListagemTimesheets();
        BLLPesquisarTimesheet pesquisarbll = new BLLPesquisarTimesheet();
        BLLTemplateFile templatebll = new BLLTemplateFile();

        //protected void Page_Init(object sender, EventArgs e)
        //{
             ///RadGrid1.NeedDataSource += RadGrid1_NeedDataSource;
        //}

        protected void Page_Load(object sender, EventArgs e)
        {
            
            gvTimesheets.ItemCommand += new GridCommandEventHandler(gvTimesheets_ItemCommand);

            #region Ajax Settings
            //Get reference to AjaxManager (from Master) 
            var manager = RadAjaxManager.GetCurrent(Page);

            //Create a new delegate to handle the AjaxRequest event 
            manager.AjaxRequest += new RadAjaxControl.AjaxRequestDelegate(RadAjaxManager1_AjaxRequest);

            //Add your ajax settings programmatically (with ref to Master manager) 
            manager.AjaxSettings.AddAjaxSetting(manager, gvTimesheets);
            #endregion

            #region Manter os valores das search box's em postback
            //Manter os valores das search box's quando é feito um postback
                if (!Page.IsPostBack)
                {
                    RecursoHumano rh = new RecursoHumano();

                    rdpUnidade.DataValueField = "ID";
                    rdpUnidade.DataTextField = "NomeUnidade";
                    rdpUnidade.DataSource = new BLLUnidades().GetAllCentrosInvestigacao();
                    rdpUnidade.DataBind();

                    // if ComboBox Unidades == Vazia
                    rdpInvestigador.DataSource = new BLLRecursoHumano().GetAll();
                    rdpInvestigador.DataValueField = "ID";
                    rdpInvestigador.DataTextField = "Nome";
                    rdpInvestigador.DataBind();
                    rdpInvestigador.Items.Insert(0, new RadComboBoxItem("", ""));

                }
            #endregion

            #region Controlos dos botoes do ficheiro template
                ///Controlos dos botoes de template (RadAsyncUpload do template file)
                var TemplateFile = templatebll.GetFile();

                if (TemplateFile != null && TemplateFile.IDTemplate > 0)
                {
                    ExportFile.Visible = true;
                    deleteFile.Visible = false; //Inativo
                    RadAsyncUploadSample.Visible = false;
                    UploadSampleFile.Visible = false;
                }
                else
                {
                    ExportFile.Visible = false;
                    deleteFile.Visible = false;
                    RadAsyncUploadSample.Visible = true;
                    UploadSampleFile.Visible = true;
                }
                #endregion

                //Ordenar por data descendente on bind
                GridSortExpression sortExpr = new GridSortExpression();
                sortExpr.FieldName = "DataEnvio";
                sortExpr.SortOrder = GridSortOrder.Descending;
                gvTimesheets.MasterTableView.SortExpressions.AddSortExpression(sortExpr);

        }

            #region Controlos do botao delete do ficheiro template
                    //Configs delete template
                    protected void deleteFile_Click(object sender, EventArgs e)
                    {
                        templatebll.DeleteFile();
                        deleteFile.Visible = false;
                        ExportFile.Visible = false;
                        RadAsyncUploadSample.Visible = true;
                        UploadSampleFile.Visible = true;
                    }
            #endregion

         protected void gvTimesheets_PreRender(object sender, EventArgs e)
        {
            if (!this.IsPostBack && this.gvTimesheets.MasterTableView.Items.Count > 1)
            {
                this.gvTimesheets.MasterTableView.Items[1].Edit = true;
                this.gvTimesheets.MasterTableView.Rebind();
            }
         }

        // bind grid a partir de ComboBox "investigador" selectedvalue
        protected void gvTimesheets_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            //if (e.RebindReason != GridRebindReason.InitialLoad)
            //{
                if (!string.IsNullOrEmpty(rdpInvestigador.SelectedValue))
                {
                    gvTimesheets.DataSource = listagembll.GetAllFiles(Convert.ToInt32(rdpInvestigador.SelectedValue));
                }
                else
                {
                    gvTimesheets.DataSource = new List<ListagemTimesheet>();
                }

                //gvTimesheets.DataSource = listagembll.GetAllFiles();
                    
            //}  
        }



        #region Insert e Update command

        protected void gvTimesheets_InsertCommand(object source, GridCommandEventArgs e)
        {

            ViewEmissaoTimeSheetEdit userControl = (ViewEmissaoTimeSheetEdit)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            //Create new row in the DataSource
            //DataRow newRow = ListagemTimesheet.SaveChanges();

            ListagemTimesheet timesheet = new ListagemTimesheet
            {
                IDRecursoHumano = int.Parse((userControl.FindControl("rdpInvestigador") as RadTextBox).Text),
                IDEstadoTimesheet = int.Parse((userControl.FindControl("rcbEstado") as RadComboBox).Text),
                AssinaturaTimesheet = (userControl.FindControl("txtAssinaturaTimesheet") as RadTextBox).Text,
                Observações = (userControl.FindControl("Obervaçoestxt") as RadTextBox).Text,
                DataEnvio = (userControl.FindControl("DataEnvio") as RadDatePicker).SelectedDate.Value,
                FileContent = Encoding.ASCII.GetBytes((userControl.FindControl("RadAsyncUpload1") as RadAsyncUpload).TargetFolder.ToString()),
            };

            //Hashtable model = new Hashtable();

            //model["IDRecursoHumano"] = (userControl.FindControl("rdpInvestigador") as RadTextBox).Text;
            //model["IDEstadoTimesheet"] = (userControl.FindControl("rdbEstado") as RadComboBox).Text;
            //model["AssinaturaTimesheet"] = (userControl.FindControl("txtAssinaturaTimesheet") as RadTextBox).Text;
            //model["Observações"] = (userControl.FindControl("Obervaçoestxt") as RadTextBox).Text;
            //model["DataEnvio"] = (userControl.FindControl("DataEnvio") as RadDatePicker).SelectedDate.ToString();
            //model["FileContent"] = (userControl.FindControl("RadAsyncUpload1") as RadAsyncUpload).TargetFolder.ToString();


            ////make sure that unique primary key value is generated 
            //model["ID"] = (int)this.Employees.Rows[this.Employees.Rows.Count - 1]["ID"] + 1;

            try
            {
                ////foreach (DictionaryEntry entry in model)
                //{
                //    //NEED HELP

                //}
                //this.Employees.Rows.Add(newRow);
                //this.Employees.AcceptChanges();

                listagembll.SaveFile(timesheet);
            }
            catch (Exception ex)
            {
                e.Canceled = true;
            }
        }

        protected void gvTimesheets_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            
            ViewEmissaoTimeSheetEdit userControl = (ViewEmissaoTimeSheetEdit)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);


            ListagemTimesheet timesheet = new ListagemTimesheet
            {
                //ID
                //IDRecursoHumano = int.Parse((userControl.FindControl("rdpInvestigador") as RadTextBox).Text),

                IDEstadoTimesheet = int.Parse((userControl.FindControl("rcbEstado") as RadComboBox).Text),
                AssinaturaTimesheet = (userControl.FindControl("txtAssinaturaTimesheet") as RadTextBox).Text,
                Observações = (userControl.FindControl("Obervaçoestxt") as RadTextBox).Text,
                DataEnvio = (userControl.FindControl("DataEnvio") as RadDatePicker).SelectedDate.Value,
                FileContent = Encoding.ASCII.GetBytes((userControl.FindControl("RadAsyncUpload1") as RadAsyncUpload).TargetFolder.ToString()),
            };

            //Hashtable model = new Hashtable();

            //model["IDRecursoHumano"] = (userControl.FindControl("rdpInvestigador") as RadTextBox).Text;
            //model["IDEstadoTimesheet"] = (userControl.FindControl("rdbEstado") as RadComboBox).Text;
            //model["AssinaturaTimesheet"] = (userControl.FindControl("txtAssinaturaTimesheet") as RadTextBox).Text;
            //model["Observações"] = (userControl.FindControl("Obervaçoestxt") as RadTextBox).Text;
            //model["DataEnvio"] = (userControl.FindControl("DataEnvio") as RadDatePicker).SelectedDate.ToString();
            //model["FileContent"] = (userControl.FindControl("RadAsyncUpload1") as RadAsyncUpload).TargetFolder.ToString();


            ////make sure that unique primary key value is generated 
            //model["ID"] = (int)this.Employees.Rows[this.Employees.Rows.Count - 1]["ID"] + 1;

            try
            {
                
                listagembll.UpdateFile(timesheet);
            }
            catch (Exception ex)
            {
                e.Canceled = true;
            }
        }

        #endregion

        protected void gvTimesheets_ItemCreated(object sender, GridItemEventArgs e) //controlar os edits
        {

            if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                GridEditableItem item = (GridEditableItem)e.Item;
                UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

                ListagemTimesheet timesheet = new ListagemTimesheet
                {
                    //ID
                    //IDRecursoHumano = int.Parse((userControl.FindControl("rdpInvestigador") as RadTextBox).Text),
                    IDEstadoTimesheet = int.Parse((userControl.FindControl("rcbEstado") as RadComboBox).Text),
                    AssinaturaTimesheet = (userControl.FindControl("txtAssinaturaTimesheet") as RadTextBox).Text,
                    Observações = (userControl.FindControl("Obervaçoestxt") as RadTextBox).Text,
                    DataEnvio = (userControl.FindControl("DataEnvio") as RadDatePicker).SelectedDate.Value,
                    FileContent = Encoding.ASCII.GetBytes((userControl.FindControl("RadAsyncUpload1") as RadAsyncUpload).TargetFolder.ToString()),
                };

                ////Automatic window edit
                //if (e.Item is GridDataItem) //grideditable
                //{
                //    HyperLink editLink = (HyperLink)e.Item.FindControl("EditLink");
                //    editLink.Attributes["href"] = "javascript:void(0);";
                //    editLink.Attributes["onclick"] = String.Format("return ShowEditForm('{0}',{1}');", e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"], e.Item.ItemIndex);

                //}
            }
        }





        //protected void gvTimesheets_ItemCreated(object sender, GridItemEventArgs e)
        //{
        //    if (e.Item is GridEditableItem)
        //    {
        //    }
        //}


        // Bind grid // Alternativa através de selectedchangeindex (x) 
        protected void ButtonListagem_Click(object sender, EventArgs e)
        {
            //gvTimesheets.DataSource = listagembll.GetAllFiles(Convert.ToInt32(rdpInvestigador.SelectedValue));
            //gvTimesheets.DataSource = null;
            gvTimesheets.Rebind();
        }


        protected void gvTimesheets_ItemUpdated(object source, Telerik.Web.UI.GridUpdatedEventArgs e)
        {
            if (e.Exception != null)
            {
                e.KeepInEditMode = true;
                e.ExceptionHandled = true;
                //DisplayMessage(true, "Customer " + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"] + " cannot be updated due to invalid data.");
            }
            else
            {
                //DisplayMessage(false, "Timesheet " + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"] + " updated");
            }
        }

        protected void gvTimesheets_ItemInserted(object source, GridInsertedEventArgs e)
        {
            if (e.Exception != null)
            {
                e.ExceptionHandled = true;
                e.KeepInInsertMode = true;
                //DisplayMessage(true, "Timesheet cannot be inserted due to invalid data.");
            }
            else
            {
                //DisplayMessage(false, "Timesheet inserted");
            }
        }


        // Eventos ajax utilizadando RadWindow
        protected void RadAjaxManagerProxy1_AjaxRequest(object sender, AjaxRequestEventArgs e) //AJAXMANAGER1
        {
            if (e.Argument == "Rebind")
            {
                gvTimesheets.MasterTableView.SortExpressions.Clear();
                gvTimesheets.MasterTableView.GroupByExpressions.Clear();
                gvTimesheets.Rebind();
            }
            else if (e.Argument == "RebindAndNavigate")
            {
                gvTimesheets.MasterTableView.SortExpressions.Clear();
                gvTimesheets.MasterTableView.GroupByExpressions.Clear();
                gvTimesheets.MasterTableView.CurrentPageIndex = gvTimesheets.MasterTableView.PageCount - 1;
                gvTimesheets.Rebind();
            }
        }

        protected void gvTimesheets_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "download_file")
            { 
            }

            if (e.CommandName == "Delete")
            {

                var ID = (int)((GridDataItem)e.Item).GetDataKeyValue("ID");
                try
                {
                    listagembll.DeleteFile(ID);
                    Page.ClientScript.RegisterStartupScript(Page.GetType(), "closethisform", "CloseAndRebind();", true);
                    gvTimesheets.Rebind();
                }
                catch (System.Exception)
                {
                    //ShowErrorMessage();
                }

            }

            if (e.CommandName == "Rebind")
            {
                gvTimesheets.MasterTableView.SortExpressions.Clear();
                gvTimesheets.MasterTableView.GroupByExpressions.Clear();
                gvTimesheets.Rebind();
            }

            if (e.CommandName == "Edit")
            {
             /*   GridEditableItem editedItem = e.Item as GridEditableItem;

                //Aceder ao UserControl
                ViewEmissaoTimeSheetEdit userControl = (ViewEmissaoTimeSheetEdit)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

                //Prepare new row to add it in the DataSource
                //DataRow[] changedRows = this.Employees.Select("ID = " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);
                //if (changedRows.Length != 1)
                {
                    gvTimesheets.Controls.Add(new LiteralControl("Unable to update."));
                    e.Canceled = true;
                    return;
                }

                 Hashtable newValues = new Hashtable();

                    newValues["IDRecursoHumano"] = (userControl.FindControl("rdpInvestigador") as RadTextBox).Text;
                    newValues["IDEstadoTimesheet"] = (userControl.FindControl("rdbEstado") as RadComboBox).Text;
                    newValues["AssinaturaTimesheet"] = (userControl.FindControl("txtAssinaturaTimesheet") as RadTextBox).Text;
                    newValues["Observações"] = (userControl.FindControl("Obervaçoestxt") as RadTextBox).Text;
                    newValues["DataEnvio"] = (userControl.FindControl("DataEnvio") as RadDatePicker).SelectedDate.ToString();
                    newValues["FileContent"] = (userControl.FindControl("RadAsyncUpload1") as RadAsyncUpload).TargetFolder.ToString();
               
                     try
                     {
                         foreach (DictionaryEntry entry in newValues)
                         {                         
                               //changedRows[0][(string)entry.Key] = entry.Value;
                         }
                         //changedRows[0].EndEdit();
                         //this.Employees.AcceptChanges();
                     } 
                     catch (System.Exception)
                     {
                         //changedRows[0].CancelEdit();
                         gvTimesheets.Controls.Add(new LiteralControl("Unable to update. Reason: " + ex.Message));
                         e.Canceled = true;
                     } */
            }


            if (e.CommandName == RadGrid.InitInsertCommandName)
            {
                /*    ViewEmissaoTimeSheetEdit userControl = (ViewEmissaoTimeSheetEdit)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
               

                   //Create new row in the DataSource
                   //DataRow newRow = ListagemTimesheet.CreateListagemTimesheet(model);
                   // DataRow newRow = this.Employees.NewRow(); EXAMPLE

                       //Insert new values
                       Hashtable newValues = new Hashtable();

                       newValues["IDRecursoHumano"] = (userControl.FindControl("rdpInvestigador") as RadTextBox).Text;
                       newValues["IDEstadoTimesheet"] = (userControl.FindControl("rdbEstado") as RadComboBox).Text;
                       newValues["AssinaturaTimesheet"] = (userControl.FindControl("txtAssinaturaTimesheet") as RadTextBox).Text;
                       newValues["Observações"] = (userControl.FindControl("Obervaçoestxt") as RadTextBox).Text;
                       newValues["DataEnvio"] = (userControl.FindControl("DataEnvio") as RadDatePicker).SelectedDate.ToString();
                       newValues["FileContent"] = (userControl.FindControl("RadAsyncUpload1") as RadAsyncUpload).TargetFolder.ToString();

                       //CREATE PK
                       //newValues["ID"] = (int)this.listagembll.InsertFile[this.listagembll.Count -- 1]["ID"] ++ 1;
                       //newValues["EmployeeID"] = (int)this.Employees.Rows[this.Employees.Rows.Count - 1]["EmployeeID"] + 1; EXAMPLE

                       try
                       {
                           foreach (DictionaryEntry entry in newValues)
                           {
                               //newRow[(string)entry.Key] = entry.Value;
                           }

                          // ListagemTimesheet.Rows.Add(newRow);
                           //ListagemTimesheet.AcceptChanges();
                           //this.Employees.Rows.Add(newRow); EXAMPLE
                           //this.Employees.AcceptChanges(); EXAMPLE
                       }
                       catch (Exception ex)
                       {
                           gvTimesheets.Controls.Add(new LiteralControl("Unable to insert . Reason: " + ex.Message));
                           e.Canceled = true;
                       } */
            }

            if (e.CommandName == "Update" && e.Item.Edit)
            {
                //Fechar form, caso o botao cancle nao funcione
                e.Canceled = true;
                e.Item.OwnerTableView.OwnerGrid.EditIndexes.Clear();
                e.Item.OwnerTableView.OwnerGrid.Rebind();
                //gvTimesheets.MasterTableView.ClearEditItems();
                //e.Canceled = true;
            }

        }


        //Aspeto conteudo nas combos

        protected void searchUnidadeInvestigacao_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((Unidades)e.Item.DataItem).NomeUnidade + " ( " + ((Unidades)e.Item.DataItem).Sigla + " )";
        }

        protected void searchInvestigador_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((RecursoHumano)e.Item.DataItem).Nome + " ( " + ((RecursoHumano)e.Item.DataItem).ID + " )";
        }


        //Controlo dos botoes command
        protected void gvTimesheets_ItemDataBound(object sender, GridItemEventArgs e)
        {

            if (rdpInvestigador.SelectedItem == null) //Nenhum RH selecionado
            {

                GridCommandItem cmditem = (GridCommandItem)gvTimesheets.MasterTableView.GetItems(GridItemType.CommandItem)[0];
                Telerik.Web.UI.RadButton addbtn = (Telerik.Web.UI.RadButton)cmditem.FindControl("AddNewRecordButton");
                addbtn.Visible = false; //Enabled
                Telerik.Web.UI.RadButton rebbtn = (Telerik.Web.UI.RadButton)cmditem.FindControl("RebindButton");
                rebbtn.Visible = false; //Enabled
            }

            else

                if (e.Item is GridEditableItem && e.Item.IsInEditMode) //(EditItem.IsInEditMode && Owner.IsItemInserted); //Estrutura edit form
                {
                    GridEditableItem item = (GridEditableItem)e.Item;

                    ViewEmissaoTimeSheetEdit userControl = e.Item.FindControl(GridEditFormItem.EditFormUserControlID) as ViewEmissaoTimeSheetEdit;

                    ListagemTimesheet timesheetedit = new ListagemTimesheet
                    {
                        //ID
                        //IDRecursoHumano = int.Parse((userControl.FindControl("rdpInvestigador") as RadTextBox).Text),

                        IDEstadoTimesheet = int.Parse((userControl.FindControl("rcbEstado") as RadComboBox).Text),
                        AssinaturaTimesheet = (userControl.FindControl("txtAssinaturaTimesheet") as RadTextBox).Text,
                        Observações = (userControl.FindControl("Obervaçoestxt") as RadTextBox).Text,
                        DataEnvio = (userControl.FindControl("DataEnvio") as RadDatePicker).SelectedDate.Value,
                        FileContent = Encoding.ASCII.GetBytes((userControl.FindControl("RadAsyncUpload1") as RadAsyncUpload).TargetFolder.ToString()),
                    };

                    foreach (GridCommandItem cmdItm in gvTimesheets.MasterTableView.GetItems(GridItemType.CommandItem)) // desativar "addNewRecord" durante edit mode
                    {
                        ListagemTimesheet timesheet = new ListagemTimesheet
                        {
                            //ID
                            //IDRecursoHumano = int.Parse((userControl.FindControl("rdpInvestigador") as RadTextBox).Text),

                            IDEstadoTimesheet = int.Parse((userControl.FindControl("rcbEstado") as RadComboBox).Text),
                            AssinaturaTimesheet = (userControl.FindControl("txtAssinaturaTimesheet") as RadTextBox).Text,
                            Observações = (userControl.FindControl("Obervaçoestxt") as RadTextBox).Text,
                            DataEnvio = (userControl.FindControl("DataEnvio") as RadDatePicker).SelectedDate.Value,
                            FileContent = Encoding.ASCII.GetBytes((userControl.FindControl("RadAsyncUpload1") as RadAsyncUpload).TargetFolder.ToString()),
                        };

                        RadButton addbtn = (RadButton)cmdItm.FindControl("AddNewRecordButton");
                        RadButton rebbtn = (RadButton)cmdItm.FindControl("Rebindbutton");
                        addbtn.Visible = false;
                        rebbtn.Visible = false;

                    }

                }

            if (e.Item is GridEditFormInsertItem && e.Item.IsInEditMode) //Estrutura insert form
            {
                GridEditableItem item = (GridEditableItem)e.Item;
                ViewEmissaoTimeSheetEdit userControl = e.Item.FindControl(GridEditFormItem.EditFormUserControlID) as ViewEmissaoTimeSheetEdit;

                ListagemTimesheet timesheet = new ListagemTimesheet
                {
                    //ID
                    //IDRecursoHumano = int.Parse((userControl.FindControl("rdpInvestigador") as RadTextBox).Text),

                    IDEstadoTimesheet = int.Parse((userControl.FindControl("rcbEstado") as RadComboBox).Text),
                    AssinaturaTimesheet = (userControl.FindControl("txtAssinaturaTimesheet") as RadTextBox).Text,
                    Observações = (userControl.FindControl("Obervaçoestxt") as RadTextBox).Text,
                    DataEnvio = (userControl.FindControl("DataEnvio") as RadDatePicker).SelectedDate.Value,
                    FileContent = Encoding.ASCII.GetBytes((userControl.FindControl("RadAsyncUpload1") as RadAsyncUpload).TargetFolder.ToString()),
                };

                foreach (GridDataItem dataItem in gvTimesheets.MasterTableView.Items)  // desativar "edit" durante insert mode
                {
                    ((Button)dataItem["EditCommandColumn"].Controls[0]).Visible = false; //RadButton
                    GridCommandItem cmdItem = (GridCommandItem)gvTimesheets.MasterTableView.GetItems(GridItemType.CommandItem)[0];
                }
            }

        }

      
        ////manualmente
        //protected void gvTimesheets_UpdateCommand(object source, GridCommandEventArgs e)
        //{
        //    var editableItem = ((GridEditableItem)e.Item);
        //    var id = (int)editableItem.GetDataKeyValue("ID");

        //    //var timesheet = gvTimesheets.DataSource.Where(n => n.ID == id).FirstOrDefault();
        //    if (timesheet != null)
        //    {
        //        editableItem.UpdateValues(timesheet);

        //        try
        //        {
        //            ListagemTimesheet.SaveChanges();
        //        }
        //        catch
        //        {
        //            ShowErrorMessage();
        //        }
        //    }
        //}

        //private void ShowErrorMessage()
        //{
        //    RadAjaxManager1.ResponseScripts.Add(string.Format("erro!\")));
        //}

       

        //    if (!this.IsPostBack && this.RadGrid1.MasterTableView.Items.Count > 1)
        //    {
        //        this.RadGrid1.MasterTableView.Items[1].Edit = true;
        //        this.RadGrid1.MasterTableView.Rebind();
        //    }
        //}


        /// Ajax bind
        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            gvTimesheets.Rebind();
        }


        protected void DataSourceTimesheets_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            e.InputParameters["login"] = this.CurrentPage.CurrentUserLogin.ToLower();
            e.InputParameters["ID"] = ID;
        }


        //Filtrar o invstigador de acordo com o CI na pesquisa
        protected void rdpUnidade_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rdpUnidade.SelectedValue != null)
            {
                var id = Convert.ToInt32(rdpUnidade.SelectedValue);
                var RecHumano = new BLLRecursoHumano();
                var res = RecHumano.GetAll().Where(x => x.IDUnidade == id).ToList();

                rdpInvestigador.DataValueField = "ID";
                rdpInvestigador.DataTextField = "Nome";
                rdpInvestigador.DataSource = res;
                rdpInvestigador.DataBind();
            }

        }


        private void DisplayMessage(string text)
        {
            gvTimesheets.Controls.Add(new LiteralControl(string.Format("<span style='color:red'>{0}</span>", text)));
        }

        private void SetMessage(string message)
        {
            gridMessage = message;
        }

        private string gridMessage = null;


        // Apagar registo da tabela
        protected void gvTimesheets_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            int ID = 0;
            ID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);
            //BLLListagemTimesheets.DeleteFile(ID);
            BLLListagemTimesheets.DeleteObject(ID);
            BLLListagemTimesheets.SaveObject();
            gvTimesheets.DataBind(); //Rebind()
        }

        protected void gvTimesheets_ItemDeleted(object source, GridDeletedEventArgs e)
        {
            if (e.Exception != null)
            {
                e.ExceptionHandled = true;
                DisplayMessage("Timesheet " + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"] + " cannot be deleted");
            }
            else
            {
                DisplayMessage("Timesheet " + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"] + " deleted");
            }
        }

        //protected void gvTimesheets_UpdateCommand(object sender, GridCommandEventArgs e)
        //{

        //}

        

       /* protected void gvTimesheets_SortCommand(object source, Telerik.Web.UI.GridSortCommandEventArgs e)
        {
            //Default sort order Descending
              if (!e.Item.OwnerTableView.SortExpressions.ContainsExpression(e.SortExpression))
                {
                    GridSortExpression sortExpr = new GridSortExpression();
                    sortExpr.FieldName = "ListagemTimesheets.DataEnvio";
                    sortExpr.SortOrder = GridSortOrder.Descending;
                    gvTimesheets.MasterTableView.SortExpressions.AddSortExpression(sortExpr);
                    gvTimesheets.MasterTableView.Rebind();

                }
        } */

        //download ficheiro da grid
        protected void link1_Click(object sender, EventArgs e) 
        {
            var ID = Convert.ToInt32(((LinkButton)sender).CommandArgument);
            var model = listagembll.GetFileByID(ID);
            if (model.FileContent != null)
            {
                if (!String.IsNullOrEmpty(Page.Request["_downloadToken"]))
                { Page.Response.Cookies.Add(new HttpCookie("_downloadToken", Page.Request["_downloadToken"])); }

                Response.Clear();
                //Response.ClearContent();
                //Response.ClearHeaders();
                Response.AddHeader("Content-Type", "Application/octet-stream");
                Response.AddHeader("Content-Length", model.FileContent.Length.ToString());
                Response.AddHeader("Content-Disposition", "attachment; filename=" + model.Ficheiro + "." + model.FileTipo); //attachment "attachment;filename=Excel_Export.xlsx
                Response.BinaryWrite(model.FileContent);
                Response.Flush();
                Response.End();
            }

            gvTimesheets.Rebind();
        }

        //Download TemplateFile
        protected void ExportFile_Click(object sender, EventArgs e) 
        {
            var IDTemplate = (((LinkButton)sender).CommandArgument);
            var model = templatebll.GetFile();
            if (model.FileContentT != null)
            {
                if (!String.IsNullOrEmpty(Page.Request["_downloadToken"]))
                { Page.Response.Cookies.Add(new HttpCookie("_downloadToken", Page.Request["_downloadToken"])); }

                Response.Clear();
                //Response.ClearContent();
                //Response.ClearHeaders();
                Response.AddHeader("Content-Type", "Application/octet-stream"); ///conversao do ficheiro binario
                Response.AddHeader("Content-Length", model.FileContentT.Length.ToString());
                Response.AddHeader("Content-Disposition", "attachment; filename=" + model.FileNameT + "." + model.FileTipoT); 
                Response.BinaryWrite(model.FileContentT);
                Response.Flush();
                Response.End(); 
            }
        }


      



        // RadAsyncFileUpload telerik para o ficheiro template
        protected void UploadSampleFile_Click(object sender, EventArgs e)
        {
            foreach (UploadedFile file in RadAsyncUploadSample.UploadedFiles)
            {
                RadAsyncUploadSample.Visible = false;
                UploadSampleFile.Visible = false;

                TemplateFile model = new TemplateFile();

                model.FileNameT = Path.GetFileNameWithoutExtension(file.FileName); //obter o nome do ficheiro do cliente
                model.FileTipoT = Path.GetExtension(file.FileName);
                file.InputStream.Position = 0;
                model.FileContentT = new byte[file.InputStream.Length];
                for (int totalBytesCopied = 0; totalBytesCopied < file.InputStream.Length; )
                    totalBytesCopied += file.InputStream.Read(model.FileContentT, totalBytesCopied, Convert.ToInt32(file.InputStream.Length) - totalBytesCopied);
                int IDTemplate = templatebll.SaveFile(model);
                if (IDTemplate > 0)
                {
                    deleteFile.Visible = true;
                    ExportFile.Visible = true;
                    RadAsyncUploadSample.Visible = false;
                    UploadSampleFile.Visible = false;

                }
                else
                {
                    deleteFile.Visible = false;
                    ExportFile.Visible = false;
                    RadAsyncUploadSample.Visible = true;
                    UploadSampleFile.Visible = true;
                }
            }
        }

        //#region Imp Página 

        //protected void gvTimesheets_ItemCreated(object sender, GridItemEventArgs e)
        //{
        //    if (e.Item is GridDataItem)
        //    {
        //        Telerik.Web.UI.DataKey keys = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex];
        //        string url =
        //           UMinho.Framework.Common.Utils.BuildViewURL(
        //                        Configurations.PopupControler,
        //                        this.ViewID, "ViewEmissaoTimeSheetEdit",
        //                        BLLFuncionalidades.GetView(Configurations.AppID, "ViewEmissaoTimeSheetEdit").Params,
        //                        new string[] { ID.ToString(), keys["ID"].ToString() },
        //                        this.CurrentPage.SPRequestQuerystring);

        //        LinkButton editLink = (LinkButton)e.Item.FindControl("imbEditTimesheet");
        //        editLink.Attributes["href"] = "#";
        //        editLink.Attributes["onclick"] = String.Format("return ShowInsertForm('{0}', '{1}','{2}');", url, "Versão de Timesheet", editLink.ClientID);
        //    }
        //}

        //protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        //{
        //    if (e.Argument == "Rebind" || e.Argument == "RebindAndNavigate")
        //    {
        //        //BindTimesheets();
        //        FormatPresentation(Utils.FormMode.EditMode);
        //    }
        //}

        //private void BindNewButton()
        //{
        //    string url =
        //          UMinho.Framework.Common.Utils.BuildViewURL(
        //                       Configurations.PopupControler,
        //                       this.ViewID, "ViewEmissaoTimeSheetEdit",
        //                       BLLFuncionalidades.GetView(Configurations.AppID, "ViewEmissaoTimeSheetEdit").Params,
        //                       new string[] { ID.ToString(), "0" },
        //                       this.CurrentPage.SPRequestQuerystring);

        //    lkbNew.Visible = true;
        //    lkbNew.Attributes["href"] = "#";
        //    lkbNew.Attributes["onclick"] = String.Format("return ShowInsertForm('{0}', '{1}', '{2}');", url, "Nova versão de timesheet", lkbNew.ClientID);
        //}

        //private void FormatPresentation(Utils.FormMode status)
        //{
        //    switch (status)
        //    {
        //        case Utils.FormMode.EditMode:

        //            // lkbVoltarProjectos.Visible = true;
        //            // pnltimesheet.Visible = true;
        //            // pnlPesquisaProjectos.Visible = false;
        //            // BindTimesheet();
        //            // LoadTitleModule(ID);
        //            BindNewButton();

        //            FormMode = Utils.FormMode.EditMode;
        //            break;

        //        case Utils.FormMode.BrowseMode:
        //            //lkbVoltarProjectos.Visible = false;
        //            // pnltimesheet.Visible = false;
        //            //pnlPesquisaProjectos.Visible = true;
        //            FormMode = Utils.FormMode.BrowseMode;
        //            break;

        //        case Utils.FormMode.CreateMode:
        //            FormMode = Utils.FormMode.CreateMode;
        //            break;

        //        case Utils.FormMode.SavedMode:
        //            FormMode = Utils.FormMode.SavedMode;
        //            break;
        //        default:
        //            break;
        //    }
        //}

        //#endregion

    }
}



        //itemcreated
        //      GridEditFormItem item = e.Item as GridEditFormItem;
        //    {
        //        if (e.Item is GridDataItem)
        //         {
        //            GridCommandItem commandItem = e.Item as GridCommandItem;
        //            RadButton addbutton = commandItem.FindControl("AddNewRecordButton") as RadButton;
        //            RadButton rebbutton = commandItem.FindControl("Rebindbutton") as RadButton;
        //            addbutton.Enabled = false;  //visible
        //            rebbutton.Enabled = false; 
        //        }
                    

        //        if (e.Item.OwnerTableView.IsItemInserted)
        //        {
        //            ViewEmissaoTimeSheetEdit GridControl = e.Item.FindControl("GridControl1") as ViewEmissaoTimeSheetEdit;
        //            GridCommandItem commandItem = e.Item as GridCommandItem;
                    
        //            RadButton rebbutton = commandItem.FindControl("Rebindbutton") as RadButton;
          
        //            rebbutton.Enabled = false; 
        //        }

        //        if (item != null && e.Item.IsInEditMode && e.Item.ItemIndex != -1)
        //        {
        //            (item.EditManager.GetColumnEditor("ID").ContainerControl.Controls[0] as TextBox).Enabled = false;
        //        }


        //    }
        //}

     /*   protected void gvTimesheets_ItemUpdated(object source, Telerik.Web.UI.GridUpdatedEventArgs e)
        {
            if (e.Exception != null)
            {
                e.KeepInEditMode = true;
                e.ExceptionHandled = true;
                //DisplayMessage(true, "Customer " + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"] + " cannot be updated due to invalid data.");
            }
            else
            {
                //DisplayMessage(false, "Timesheet " + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"] + " updated");
            }
        }  */

  