﻿using IdentityKey.Areas.Admin.Models;
using IdentityKey.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace IdentityKey.Areas.Admin.Controllers
{
    //[Authorize(Roles = "Admin")]
    public class MailController 
        : BaseAdminController
    {
        private readonly IMailRepository mailRepo = null;

        public MailController()
        {
            this.mailRepo = new MailRepository();
        }

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

        [HttpPost]
        public JsonResult MailList()
        {
            try
            {
                List<Mail> mails = mailRepo.GetAll().ToList();

                return Json(new { Result = "OK", Records = mails, TotalRecordCount = mails.Count });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        public JsonResult CreateMail(Mail mail)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "Form is not valid! " +
                        "Please correct it and try again."
                    });
                }

                mailRepo.Add(mail);
                var addedMail = mailRepo.FindBy(d => d.Id == mail.Id);
                return Json(new { Result = "OK", Record = addedMail });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        public JsonResult UpdateMail(Mail mail)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "Form is not valid! " +
                          "Please correct it and try again."
                    });
                }

                mailRepo.Edit(mail);
                return Json(new { Result = "OK" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        public JsonResult DeleteMail(Mail mail)
        {
            try
            {
                Mail todelete = mailRepo.FindBy(d => d.Id == mail.Id).FirstOrDefault();

                mailRepo.Delete(todelete);

                return Json(new { Result = "OK" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

    }
}