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)
        {
            User user = _service.Find(id);
            if (user != null)
            {
                string name = ControllerContext.HttpContext.User.Identity.Name;
                var LogInUser = _service.FindOne(u => u.Login == name);
                if (LogInUser.Id == user.Id)
                {
                    return View(_service.Find(id));
                }
                else
                {
                    ViewData["message"] = "error_user";
                    return View("Confirm"); 
                }

            }
            ViewData["message"] = "error";
            return View("Confirm");          
        }

        [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);
        }
    }
}