//public ReturnBookForm()
 //{
 //    InitializeComponent();
 //}
 public ReturnBookForm(Feature feature, RentalDTO selectedRental)
 {
     InitializeComponent();
     _feature = feature;
     _rental = selectedRental;
     InitializeData();
 }
 //public ExpandRentalForm()
 //{
 //    InitializeComponent();
 //}
 public ExpandRentalForm(Feature feature, RentalDTO rentalDto)
 {
     InitializeComponent();
     _feature = feature;
     _rental = rentalDto;
     InitializeData();
 }
        private void BtnSaveClick(object sender, EventArgs e)
        {
            string msg = ValidateData();
            if (msg != null)
            {
                MessageBox.Show(this, msg, Constants.SYSTEM_INFO, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            var rentalDto = new RentalDTO();
            rentalDto.Barcode = txtBarcode.Text;
            rentalDto.UserId = txtUser.Text;
            rentalDto.Status = RentalStatus.NEW;
            rentalDto.IssueDate = dteIssuedDate.Value;
            rentalDto.DueDate = dteDueDate.Value;

            if (_feature.AddRental(rentalDto))
            {
                MessageBox.Show(this, Constants.RENTAL_INSERT_OK, Constants.SYSTEM_INFO, MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                _listRental.Add(rentalDto);
            } else
            {
                MessageBox.Show(this, Constants.SYSTEM_ERROR, Constants.SYSTEM_INFO, MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            Dispose();
        }
        public List<RentalDTO> GetByBarcode(string barcode)
        {
            List<RentalDTO> listRental = new List<RentalDTO>();

            try
            {
                SqlDataReader reader = ConnectionManager.GetCommand("SP0901ByBarcode",
                                                                    new Dictionary<string, SqlDbType>()
                                                                        {
                                                                            {"@Barcode", SqlDbType.NVarChar}
                                                                        },
                                                                    new List<object>()
                                                                        {
                                                                            barcode
                                                                        }).ExecuteReader();
                RentalDTO rental;

                while (reader.Read())
                {
                    rental = new RentalDTO();
                    rental.UserId = reader["UserID"].ToString();
                    rental.Barcode = reader["Barcode"].ToString();
                    rental.IssueDate = (DateTime)reader["IssuedDate"];
                    rental.DueDate = (DateTime)reader["DueDate"];
                    rental.ReturnDate = (DateTime)reader["ReturnDate"];
                    float fine;
                    float.TryParse(reader["Fine"].ToString(), out fine);
                    rental.Fine = fine;
                    int status;
                    int.TryParse(reader["Status"].ToString(), out status);
                    rental.Status = (RentalStatus)Enum.Parse(typeof(RentalStatus), status.ToString());
                    int expandCount;
                    int.TryParse(reader["ExpandCount"].ToString(), out expandCount);
                    rental.ExpandCount = expandCount;
                    rental.CreatedDate = (DateTime)reader["CreatedDate"];
                    rental.UpdatedDate = (DateTime)reader["UpdatedDate"];

                    listRental.Add(rental);
                }
            }
            catch (Exception e)
            {
                Log.Error("Error at RentalDAO - GetByBarcode", e);
                return null;
            }

            return listRental;
        }
        public bool ReturnBook(RentalDTO rentalDto)
        {
            try
            {
                // Update Rental Status
                if (!rentalBus.UpdateRental(rentalDto))
                {
                    return false;
                }

                // Update BookCopy Status, Catalogue AvailableCopies
                var copyDto = copyBus.GetCopyById(rentalDto.Barcode);
                if (copyDto != null)
                {
                    var catalogeDto = catalogeBus.GetCatalogueById(copyDto.ISBN);

                    if (catalogeDto != null)
                    {
                        if (rentalDto.Status == RentalStatus.FISNISHED)
                        {
                            // copy status needs to be updated later
                            // ++ DiepTN: 2012/03/12 - Update
                            copyDto.Status = (int)CopyStatus.AVAILABLE;
                            // --
                            catalogeDto.AvailableCopies++;
                        }
                        else if (rentalDto.Status == RentalStatus.DAMAGED)
                        {
                            // copy status needs to be updated later
                            // ++ DiepTN: 2012/03/12 - Update
                            copyDto.Status = (int)CopyStatus.DAMAGED;
                            // --
                            catalogeDto.AvailableCopies++;
                        }
                        else if (rentalDto.Status == RentalStatus.LOST)
                        {
                            // copy status needs to be updated later
                            // ++ DiepTN: 2012/03/12 - Update
                            copyDto.Status = (int)CopyStatus.LOST;
                            // --
                            // availablecopies
                        }

                        copyBus.UpdateCopy(copyDto);
                        catalogeBus.UpdateCatalogue(catalogeDto, null);
                    }
                }

            }
            catch (Exception e)
            {
                Log.Error("Error at Feature - ReturnBook", e);
            }
            return false;
        }
        public bool ExpandRental(RentalDTO rentalDto)
        {
            try
            {
                // check ExpandLimit
                if (rentalDto.ExpandCount >= rentalDto.ExpandLimit)
                {
                    Log.Error("Error at Feature - ExpandRental: Maximum expand time has been reached.");
                    return false;
                }

                // update Rental status
                rentalDto.ExpandCount++;
                return rentalBus.UpdateRental(rentalDto);
            }
            catch (Exception e)
            {
                Log.Error("Error at Feature - ExpandRental", e);
            }
            return false;
        }
        public string ApproveRequest(BookRegisterDTO registerDto)
        {
            try
            {
                // Update BookCopy Status
                var listAvailableCopy = GetAvailableCopy(registerDto.ISBN);
                if (listAvailableCopy.Count <= 0)
                {
                    return "Không còn sách khả dụng!";
                }

                // Update Register status
                registerDto.Status = BookRegisterStatus.APPROVED;
                if (!registerBus.UpdateBookRegister(registerDto))
                {
                    return Constants.SYSTEM_ERROR;
                }

                // Add Rental
                var rentalDto = new RentalDTO();
                rentalDto.UserId = registerDto.UserId;
                rentalDto.Barcode = listAvailableCopy[0].Barcode;
                rentalDto.Status = RentalStatus.NEW;
                rentalDto.IssueDate = DateTime.Now;
                rentalDto.DueDate = DateTime.Now.AddDays(7);
                AddRental(rentalDto);

                // Send mail to Reader
                var userDto = userBus.GetUserById(registerDto.UserId);
                if (userDto != null)
                {
                    var writer = new StringWriter();
                    var html = new HtmlTextWriter(writer);
                    html.WriteEncodedText(String.Format("Thân gửi {0}.", userDto.Username));
                    html.WriteEncodedText(" Yều cầu của bạn đã được chấp nhận.");
                    html.WriteEncodedText(String.Format(" Tên sách: {0}", registerDto.BookTitle));
                    html.WriteEncodedText(String.Format(" Ngày đăng ký: {0}", registerDto.RegisterDate.ToShortDateString()));
                    html.WriteEncodedText(String.Format(" Ngày yêu cầu được chấp nhận: {0}", DateTime.Now.ToShortDateString()));
                    html.WriteEncodedText(" Mời bạn đến nhận sách.");
                    SendSampleMail(userDto.Email, Options.MailSubject, writer.ToString());
                }
            }
            catch (Exception e)
            {
                Log.Error("Error at Feature - ApproveRequest", e);
            }

            return null;
        }
        public bool AddRental(RentalDTO rentalDto)
        {
            try
            {
                // insert rental
                rentalDto.Status = RentalStatus.NEW;
                if (!rentalBus.InsertRental(rentalDto))
                {
                    return false;
                }

                // update BookCopy Status
                var copyDto = copyBus.GetCopyById(rentalDto.Barcode);
                if (copyDto != null)
                {
                    copyDto.Status = (int)CopyStatus.NOT_AVAIABLE;
                    copyBus.UpdateCopy(copyDto);

                    // update Catalogue AvailableCopies
                    var catalogeDto = catalogeBus.GetCatalogueById(copyDto.ISBN);
                    if (catalogeDto != null)
                    {
                        catalogeDto.AvailableCopies--;
                        // ++ 2012/04/05 - DiepTN: Add
                        catalogeDto.RentalTime++;
                        // --
                        catalogeBus.UpdateCatalogue(catalogeDto, null);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("Error at Feature - AddRental", e);
            }

            return true;
        }
 public bool UpdateRental(RentalDTO rental)
 {
     return _rentalDao.Update(rental);
 }
 public bool InsertRental(RentalDTO rental)
 {
     return _rentalDao.Insert(rental);
 }
        public List<RentalDTO> SearchRentalsAllStt(SearchRentalDTO dto)
        {
            RentalDTO rentalDto;
            List<RentalDTO> list = new List<RentalDTO>();
            try
            {
                SqlDataReader reader = ConnectionManager.GetCommand("sp0004AllStt",
                                                                    new Dictionary<string, SqlDbType>()
                                                                        {
                                                                            {"@userName", SqlDbType.NVarChar},
                                                                            {"@title", SqlDbType.NVarChar},
                                                                            {"@fromDate", SqlDbType.DateTime},
                                                                            {"@toDate", SqlDbType.DateTime}
                                                                        },
                                                                    new List<object>()
                                                                        {
                                                                            dto.UserName,
                                                                            dto.Title,
                                                                            dto.FromDate,
                                                                            dto.ToDate
                                                                        }).ExecuteReader();

                while (reader.Read())
                {
                    rentalDto = new RentalDTO();
                    rentalDto.Username = reader["Username"].ToString();
                    rentalDto.BookTitle = reader["Title"].ToString();
                    rentalDto.Barcode = reader["Barcode"].ToString();
                    rentalDto.IssueDate = DateTime.Parse(reader["IssuedDate"].ToString());
                    rentalDto.DueDate = DateTime.Parse(reader["DueDate"].ToString());
                    if (reader["ReturnDate"] == DBNull.Value)
                    {
                        rentalDto.ReturnDate = null;
                    }
                    else
                    {
                        rentalDto.ReturnDate = DateTime.Parse(reader["ReturnDate"].ToString());
                    }
                    float fine;
                    float.TryParse(reader["Fine"].ToString(), out fine);
                    rentalDto.Fine = fine;
                    int status;
                    int.TryParse(reader["Status"].ToString(), out status);
                    rentalDto.Status = (RentalStatus)Enum.Parse(typeof(RentalStatus), status.ToString());
                    int expandCount;
                    int.TryParse(reader["ExpandCount"].ToString(), out expandCount);
                    rentalDto.ExpandCount = expandCount;
                    list.Add(rentalDto);
                }

                reader.Close();
            }
            catch (Exception e)
            {
                Log.Error("Error at AuthorDAO - GetAuthorByID", e);
                return null;
            }
            return list;
        }
        public bool Update(RentalDTO rental)
        {
            try
            {
                rental.UpdatedDate = DateTime.Now;
                ConnectionManager.GetCommand("SP0903",
                                             new Dictionary<string, SqlDbType>()
                                                 {
                                                     {"@UserID", SqlDbType.NVarChar},
                                                     {"@Barcode", SqlDbType.NVarChar},
                                                     {"@IssuedDate", SqlDbType.DateTime},
                                                     {"@DueDate", SqlDbType.DateTime},
                                                     {"@ReturnDate", SqlDbType.DateTime},
                                                     {"@Fine", SqlDbType.Float},
                                                     {"@Status", SqlDbType.Int},
                                                     {"@ExpandCount", SqlDbType.Int},
                                                     {"@CreatedDate", SqlDbType.DateTime},
                                                     {"@UpdatedDate", SqlDbType.DateTime}
                                                 },
                                             new List<object>()
                                                 {
                                                     rental.UserId,
                                                     rental.Barcode,
                                                     rental.IssueDate,
                                                     rental.DueDate,
                                                     //if ReturnDate is null, insert null to DB
                                                     rental.ReturnDate ?? SqlDateTime.Null,
                                                     rental.Fine,
                                                     rental.Status,
                                                     rental.ExpandCount,
                                                     rental.CreatedDate,
                                                     rental.UpdatedDate
                                                 }).ExecuteNonQuery();

                return true;
            }
            catch (Exception e)
            {
                Log.Error("Error at RentalDAO - Update", e);
                return false;
            }
        }
        public List<RentalDTO> GetByUserIdPaging(string userId, int start, int end, out int noR)
        {
            List<RentalDTO> listRental = new List<RentalDTO>();

            try
            {
                noR = (int) ConnectionManager.GetCommand("SP0901ByUserIDPagingC",
                                                         new Dictionary<string, SqlDbType>()
                                                             {
                                                                 {"@UserID", SqlDbType.NVarChar}
                                                             },
                                                         new List<object>()
                                                             {
                                                                 userId
                                                             }).ExecuteScalar();

                if (noR != 0)
                {
                    SqlDataReader reader = ConnectionManager.GetCommand("SP0901ByUserIDPaging",
                                                                        new Dictionary<string, SqlDbType>()
                                                                            {
                                                                                {"@UserID", SqlDbType.NVarChar},
                                                                                {"@StartRow", SqlDbType.NVarChar},
                                                                                {"@EndRow", SqlDbType.NVarChar}
                                                                            },
                                                                        new List<object>()
                                                                            {
                                                                                userId,
                                                                                start,
                                                                                end
                                                                            }).ExecuteReader();
                    RentalDTO rental;

                    while (reader.Read())
                    {
                        rental = new RentalDTO();
                        rental.UserId = reader["UserID"].ToString();
                        rental.Barcode = reader["Barcode"].ToString();
                        rental.IssueDate = (DateTime) reader["IssuedDate"];
                        rental.DueDate = (DateTime) reader["DueDate"];
                        if (reader["ReturnDate"] == DBNull.Value)
                        {
                            rental.ReturnDate = null;
                        }
                        else
                        {
                            rental.ReturnDate = (DateTime) reader["ReturnDate"];
                        }
                        float fine;
                        float.TryParse(reader["Fine"].ToString(), out fine);
                        rental.Fine = fine;
                        int status;
                        int.TryParse(reader["Status"].ToString(), out status);
                        rental.Status = (RentalStatus) Enum.Parse(typeof (RentalStatus), status.ToString());
                        int expandCount;
                        int.TryParse(reader["ExpandCount"].ToString(), out expandCount);
                        rental.ExpandCount = expandCount;
                        rental.CreatedDate = (DateTime) reader["CreatedDate"];
                        rental.UpdatedDate = (DateTime) reader["UpdatedDate"];

                        listRental.Add(rental);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("Error at RentalDAO - GetByUserIDPaging", e);
                noR = 0;
                return null;
            }

            return listRental;
        }