using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using FourLayer.ApplicationLogic;
using FourLayer.BusinessEntity;

namespace Chapter14
{
   /// <summary>
   /// Część konsumenta
   /// </summary>
   public class BookListConsumer : WebPart
   {
      private Publisher _publisher = null;

      public BookListConsumer()
      {
         Title = "Pokaż książki";
         Description = "Pokaż wszystkie książki";
         TitleIconImageUrl = "images/webpartBooks.gif";
         CatalogIconImageUrl = "images/webpartBooks.gif";         
      }

      public Publisher PublisherToUse
      {
         get { return _publisher; }
         set { 
            _publisher = value;
            Title = "Pokaż książki wydawnictwa " + _publisher.Name;
         }
      }

      protected override void RenderContents(HtmlTextWriter writer)
      {
         // pobierz zbiór książek wybranego wydawcy
         EntityCollection<Book> books =
            BookCatalogLogic.GetBooksByPublisher(PublisherToUse.Id);

         // wyświetl nie więcej niż 10 pierwszych książek
         int max = 10;
         if (max > books.Count) max = books.Count;
         string output = "<div id='listContainer'>";
         for (int i = 0; i < max; i++)
         {
            Book book = books[i];
            output += "<p><a href=BookDetails.aspx?id=";
            output += book.Isbn + ">";
            output += book.Title;
            output += "></p>";
         }
         output += "</div>";
         writer.Write(output);
      }


      private ISelectPublisher _pubInterface;

      /// <summary>
      /// Definiuje punkt połączenia
      /// </summary>
      [ConnectionConsumer("SelectedPublisherConnectionPoint")]
      public void GetProvider(ISelectPublisher pubInterface)
      {
         _pubInterface = pubInterface;
      }

      /// <summary>
      /// Pobiera wydawcę od dostawcy
      /// </summary>
      protected override void OnPreRender(EventArgs e)
      {
         if (_pubInterface != null)
         {
            PublisherToUse = _pubInterface.ChosenPublisher;
         }
      }

   }
}
