using System.Linq;
using System.Web.Mvc;
using Wierszowki.Core.Interfaces;
using Wierszowki.Core.Linq;
using Wierszowki.Services;
using Wierszowki.Services.Interfaces;
using xVal.ServerSide;

namespace Wierszowki.Controllers
{
    [HandleError]
    [Authorize]
    public class UserController : Controller
    {
        private readonly IUserService _service;

        public UserController()
        {
            _service = new UserService(new LinqRepository<User>());
        }

        public UserController(IUserService service)
        {
            _service = service;
        }

        public ActionResult Index()
        {
            var users = _service.FindAll();
            return View(users);
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Create()
        {
            return View(new User());
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(User user)
        {
            try
            {
                _service.Create(user);
            }
            catch (RulesException ex)
            {
                ex.AddModelStateErrors(ModelState, "user");
            }

            if (ModelState.IsValid)
                return View("Confirm", user);

            return View(user);
        }

        [Authorize]
        public ActionResult Confirm(User user)
        {
            return View(user);
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int id)
        {
            return View(_service.Find(id));
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(User user)
        {
            try
            {
                _service.Update(user);
            }
            catch (RulesException ex)
            {
                ex.AddModelStateErrors(ModelState, "user");
            }

            if (ModelState.IsValid)
                return View("Confirm", user);


            return View(user);
        }
    }
}