using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using KendoDateSample.Models;
using KendoDateSample.Models.Repositories;

namespace KendoDateSample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["usertypes"] = UserTypeRepository.All();

            return View();
        }

        public ActionResult UsersRead([DataSourceRequest] DataSourceRequest request)
        {
            return Json(UserRepository.All().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UsersUpdate([DataSourceRequest] DataSourceRequest request, UserModel model)
        {
            ValidateUser(model);

            if (ModelState.IsValid)
            {
                UserRepository.Update(model);
            }
            return Json(ModelState.IsValid ? new object() : ModelState.ToDataSourceResult());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UsersDestroy([DataSourceRequest] DataSourceRequest request, UserModel model)
        {
            UserRepository.Delete(model.Id);
            return Json(ModelState.IsValid ? new object() : ModelState.ToDataSourceResult());
        }


        public ActionResult About(int id)
        {
            var user = UserRepository.One(id);
            return View(user);
        }

        [HttpPost]
        public ActionResult UpdateProfile(UserModel model)
        {
            var success = false;
            var isEmailValid = false;
            var isPasswordValid = false;
            var isPasswordConfirmValid = false;

            ValidateUser(model);
            isEmailValid = model.ValidateEmail();
            isPasswordValid = model.ValidatePassword();
            isPasswordConfirmValid = model.ValidatePasswordConfirm();

            if (ModelState.IsValid)
            {
                success = UserRepository.Update(model);
            }

            var result = new
            {
                success = success,
                isEmailValid = isEmailValid,
                isPasswordValid = isPasswordValid,
                isPasswordConfirmValid = isPasswordConfirmValid
            };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public List<SelectListItem> ValidateUser(UserModel model)
        {
            if (model == null) return null;

            var list = new List<SelectListItem>();
            var isValid = model.ValidateEmail();
            var fieldName = string.Empty;
            var error = string.Empty;



            if (!isValid)
            {
                fieldName = "Email";
                error = "Email is already in use!";
                list.Add(new SelectListItem()
                {
                    Text = error,
                    Value = fieldName
                });
                ModelState.AddModelError(fieldName, error);
            }

            isValid = model.ValidatePassword();

            if (!isValid)
            {
                fieldName = "PasswordUnEncrypted";
                error = "Passwords must be at least 8 characters & 1 digit.";
                list.Add(new SelectListItem()
                {
                    Text = error,
                    Value = fieldName
                });
                ModelState.AddModelError(fieldName, error);
            }


            isValid = model.ValidatePasswordConfirm();

            if (!isValid)
            {
                fieldName = "PasswordConfirm";
                error = "Password and Confirm PW do not match.";
                list.Add(new SelectListItem()
                {
                    Text = error,
                    Value = fieldName
                });
                ModelState.AddModelError(fieldName, error);
            }

            return list.Count > 0 ? list : null;
        }

        public ActionResult GetUserTypes()
        {
            var list = UserTypeRepository.All();
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetStates()
        {
            List<SelectListItem> list = null;

            using (var context = new FPSTestEntities())
            {
                list = (from x in context.States.AsEnumerable()
                        select new SelectListItem
                        {
                            Text = x.Name,
                            Value = x.Id
                        }).OrderBy(x => x.Text).ToList();
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetRegionalServiceConsultants()
        {
            List<SelectListItem> list = null;

            using (var context = new FPSTestEntities())
            {
                list = (from x in context.Users.Where(x => x.UserTypeId == (byte)Enums.UserTypes.RegionalServiceConsultant).AsEnumerable()
                        select new SelectListItem
                        {
                            Text = string.Format("{0}, {1}", x.LastName, x.FirstName),
                            Value = x.Id.ToString()
                        }).OrderBy(x => x.Text).ToList();
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetServiceConsultants()
        {
            List<SelectListItem> list = null;

            using (var context = new FPSTestEntities())
            {
                list = (from x in context.Users.Where(x => x.UserTypeId == (byte)Enums.UserTypes.ServiceConsultant).AsEnumerable()
                        select new SelectListItem
                        {
                            Text = string.Format("{0}, {1}", x.LastName, x.FirstName),
                            Value = x.Id.ToString()
                        }).OrderBy(x => x.Text).ToList();
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetProviders()
        {
            List<SelectListItem> list = null;

            using (var context = new FPSTestEntities())
            {
                list = (from x in context.Users.Where(x => x.UserTypeId == (byte)Enums.UserTypes.Provider).AsEnumerable()
                        select new SelectListItem
                        {
                            Text = string.Format("{0}, {1}", x.LastName, x.FirstName),
                            Value = x.Id.ToString()
                        }).OrderBy(x => x.Text).ToList();

                list.Insert(0, new SelectListItem() { Text = "None", Value = "0" });
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetMobileCarriers()
        {
            List<SelectListItem> list = null;

            using (var context = new FPSTestEntities())
            {
                list = (from x in context.MobileCarriers.AsEnumerable()
                        select new SelectListItem
                        {
                            Text = x.Name,
                            Value = x.Id.ToString()
                        }).OrderBy(x => x.Text).ToList();
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }
    }
}
