using Library.Domain.Abstract;
using Library.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Library.Presentation.Controllers
{
    public class BookController : Controller
    {
        private IBookRepository repository;

        public BookController(IBookRepository repository)
        {
            this.repository = repository;
        }

        public ViewResult List(string genre)
        {
            IEnumerable<Book> books =
                repository.Books.Where(b => genre == null || b.Genre == genre);
            return View(books);
        }

        public ViewResult Edit(int bookID)
        {
            Book book = repository.Books
                        .FirstOrDefault(b => b.ID == bookID);
            return View(book);
        }

        [HttpPost]
        public ActionResult Edit(Book book)
        {
            if (ModelState.IsValid)
            {
                repository.SaveBook(book);
                TempData["bookSaved"]
                    = String.Format("The book \"{0}\" has been succesfully saved.",
                                    book.Name);
                return RedirectToAction("List", "Book");
            }
            else
            {
                return View(book);
            }
        }

        public ViewResult Create()
        {
            return View("Edit", new Book());
        }

        [HttpPost]
        public RedirectToRouteResult Delete(int bookID)
        {
            string bookName = repository.DeleteBook(bookID);
            if (bookName != null)
            {
                TempData["bookDeleted"] = 
                    String.Format("The book \"{0}\" was deleted", bookName);
            }
            return RedirectToAction("List");
        }
    }
}