using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using r13.Models;
using Microsoft.Web.Mvc;
using r13.Helpers;

namespace r13.Controllers
{
    public class RegistrationController : Controller
    {

        public ViewResult Index()
        {
            return View();
        }

        public ActionResult SubmitRegistration(string myCaptcha, string attempt)
        {
            if (CaptchaHelper.VerifyAndExpireSolution(HttpContext, myCaptcha, attempt))
            {
                // W rzeczywistej aplikacji zarejestruj użytkownika 
                return Content("Prawidłowo");
            }
            else
            {
                // Ponownie wyświetl widok z komunikatem błędu 
                ModelState.AddModelError("attempt", "Nieprawidłowo - spróbuj jeszcze raz");
                return View("Index");
            }
        }


        private RegistrationData regData; // Wypełnimy go później 

        public ActionResult BasicDetails(string nextButton)
        {
            if ((nextButton != null) && ModelState.IsValid)
                return RedirectToAction("ExtraDetails");
            return View(regData);
        }

        public ActionResult ExtraDetails(string backButton, string nextButton)
        {
            if (backButton != null )
                return RedirectToAction("BasicDetails");
            else if ((nextButton != null) && ModelState.IsValid)
                return RedirectToAction("Confirm");
            else
                return View(regData);
        }

        public ActionResult Confirm(string backButton, string nextButton)
        {
            if (backButton != null)
                return RedirectToAction("ExtraDetails");
            else if (nextButton != null)
                return RedirectToAction("Complete");
            else
                return View(regData);
        }

        public ActionResult Complete()
        {
            // Zapisanie regData do bazy danych, wygenerowanie widoku "zakończone"
            return Content("Gotowe");
        } 

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var serialized = Request.Form["regData"];
            if (serialized != null)
            { // Został wysłany formularz z serializowanymi danymi 
                regData = (RegistrationData)new MvcSerializer().Deserialize(serialized);
                TryUpdateModel(regData);
            }
            else
                regData = (RegistrationData)TempData["regData"] ?? new RegistrationData();
        }

        protected override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (filterContext.Result is RedirectToRouteResult)
                TempData["regData"] = regData;
        } 

    }
}
