using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IdeaBladeMVC.Data;
using IdeaBladeMVC.Models;

namespace IdeaBladeMVC.Controllers {
  public class CustomersController : Controller {
    private readonly ICustomerRepository customerRepository;

    public CustomersController()
      : this(new CustomerRepository()) {
    }

    public CustomersController(ICustomerRepository customerRepository) {
      this.customerRepository = customerRepository;
    }

    public ViewResult Index() {
      return View(customerRepository.GetAllCustomers());
    }

    public ViewResult Details(Guid id) {
      return View(customerRepository.GetById(id));
    }

    public ActionResult Create() {
      return View();
    }

    [HttpPost]
    public ActionResult Create(Customer customer) {
      if (ModelState.IsValid) {
        customerRepository.InsertOrUpdate(customer);
        customerRepository.Save();
        return RedirectToAction("Index");
      } else {
        return View();
      }
    }

    public ActionResult Edit(Guid id) {
      return View(customerRepository.GetById(id));
    }

    [HttpPost]
    public ActionResult Edit(Customer customer) {
      if (ModelState.IsValid) {
        customerRepository.InsertOrUpdate(customer);
        customerRepository.Save();
        return RedirectToAction("Index");
      } else {
        return View();
      }
    }

    public ActionResult Delete(Guid id) {
      return View(customerRepository.GetById(id));
    }

    [HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(Guid id) {
      customerRepository.Delete(id);
      customerRepository.Save();

      return RedirectToAction("Index");
    }
  }
}