namespace ServiceCenter.Controllers
{
    #region Using
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using Data = ServiceCenter.Data.DapperNet;
    #endregion

    public class EmployeeController : Controller
    {
        #region Список
        public ActionResult Index()
        {
            ViewBag.Title = "Сотрудники";

            Data.DataService ds = new Data.DataService();
            List<Data.Employee> employees = ds.GetEmployees().OrderBy(x => x.SurName).ThenBy(x => x.Name).ToList();

            return View(employees);
        }
        #endregion

        #region Создание
        public ActionResult Create()
        {
            ViewBag.Title = "Сотрудники - добавление записи";

            return View();
        }

        [HttpPost]
        public ActionResult Create(Data.Employee employee, FormCollection collection)
        {
            ViewBag.Title = "Сотрудники - добавление записи";

            int positionId = 0;

            if (!Int32.TryParse(collection["PositionId"], out positionId))
                ModelState.AddModelError("Position", "Выберите должность!");

            if (!ModelState.IsValid)
                return View(employee);

            employee.PositionId = positionId;

            Data.DataService ds = new Data.DataService();

            try
            {
                ds.SaveEmployee(employee);
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", string.Format("При создании записи возникла ошибка:{0}{1}", Environment.NewLine, ex.Message));
                return View(employee);
            }
        }
        #endregion

        #region Редактирование
        public ActionResult Edit(int id)
        {
            ViewBag.Title = "Сотрудники - редактирование записи";

            Data.DataService ds = new Data.DataService();
            Data.Employee employee = ds.GetEmployee(id);

            ViewBag.Message = employee.FullName;

            return View(employee);
        }

        [HttpPost]
        public ActionResult Edit(Data.Employee employee, FormCollection collection)
        {
            ViewBag.Title = "Сотрудники - редактирование записи";

            Data.DataService ds = new Data.DataService();

            ViewBag.Message = ds.GetEmployee(employee.EmployeeId).FullName;

            int positionId = 0;

            if (!Int32.TryParse(collection["PositionId"], out positionId))
                ModelState.AddModelError("Position", "Выберите должность!");

            if (!ModelState.IsValid)
                return View(employee);

            employee.PositionId = positionId;

            try
            {
                ds.SaveEmployee(employee);
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", string.Format("При редактировании записи возникла ошибка:{0}{1}", Environment.NewLine, ex.Message));
                return View(employee);
            }
        }
        #endregion

        #region Удаление
        public ActionResult Delete(int id)
        {
            Data.DataService ds = new Data.DataService();
            Data.Employee employee = ds.GetEmployee(id);

            ds.DeleteEmployee(employee);

            return RedirectToAction("Index");
        }
        #endregion

        #region DropDown
        public ActionResult GetEmployeeDropDown(int selectedId)
        {
            Data.DataService ds = new Data.DataService();

            ViewData.Model = ds.GetEmployees().OrderBy(x => x.SurName).ThenBy(x => x.Name).Select(x => new SelectListItem()
            {
                Text = x.FullName,
                Value = x.EmployeeId.ToString(),
                Selected = x.EmployeeId == selectedId
            });

            ViewData.ModelMetadata = new ModelMetadata(ModelMetadataProviders.Current, null, null, typeof(int), "EmployeeId")
            {
                NullDisplayText = "выберите сотрудника"
            };

            return View("DropDown");
        }
        #endregion
    }
}
