using System;
using System.Linq;
using System.Web.Mvc;
using Wierszowki.Core.Linq;
using Wierszowki.Models;
using Wierszowki.Services;
using xVal.ServerSide;
using System.Collections.Generic;
using Wierszowki.Core.Interfaces;

namespace Wierszowki.Controllers
{
    public class MagazineItemController : Controller
    {
        private readonly WierszowkiDataContext _context;
        private readonly MagazineItemService _service;

        public MagazineItemController()
        {
            _context = new WierszowkiDataContext();
            _service = new MagazineItemService();
        }

        public ActionResult Index()
        {
            return RedirectToAction("Index", "Report");
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Get)]
        [OutputCache(Duration = 10, VaryByParam = "none")]
        public ActionResult Create()
        {
            var viewData = InitMagazineItemViewData();
            return View(viewData);
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(MagazineItem magazineItem)
        {
            try
            {
                _service.Create(magazineItem, ControllerContext.HttpContext.User.Identity.Name);
                ModelState.Clear();
            }
            catch (RulesException ex)
            {
                ex.AddModelStateErrors(ModelState, "magazineItem");
            }

            if (ModelState.IsValid)
            {
                Info inf = InitInfo("1", 0, 0, 0);
                var confirmViewData = new ConfirmViewData();
                confirmViewData = InitConfirmViewData(_context.Authors.Single(a => a.Id == magazineItem.AuthorId), OperationType.Create, inf);
                return View("Confirm", confirmViewData);
            }
            var viewData = InitMagazineItemViewData();
            viewData.MagazineItem = magazineItem;

            return View(viewData);
        }

        [Authorize]
        public ActionResult Confirm(Author author)
        {
            return View(author);
        }

        [Authorize]
        public ActionResult Edit(string id, string powrot, string month, string year, string user_id)
        {
            int id1 = 0;
            int month1 = (month != null) ? Convert.ToInt32(month) : 0;
            int year1 = (year != null) ? Convert.ToInt32(year) : 0;
            int user1 = (user_id != null) ? Convert.ToInt32(user_id) : 0;
            try
            {
                id1 = (id != null) ? Convert.ToInt32(id) : 0;
            }
            catch
            {
            }
            var viewData = InitMagazineItemViewData();
            var magazineItem = _service.Find(id1);

            if (magazineItem == null)
            {
                Info inf = InitInfo(powrot, month1, year1, user1);
                var confirmViewData = new ConfirmViewData();

                if (id != "")     //nie znaleziono w bazie wierszowki o zadanym id
                {
                    confirmViewData = InitConfirmViewData(null, OperationType.WrongId, inf);
                }
                else              //nie podano numeru id
                {
                    confirmViewData = InitConfirmViewData(null, OperationType.NullId, null);
                }
                return View("Confirm", confirmViewData);
            }
            viewData.MagazineItem = magazineItem;
            viewData.Magazine = magazineItem.Issue.Magazine;
            viewData.Issue = magazineItem.Issue;
            viewData.Info = InitInfo(powrot, month1, year1, user1);

            var startDate = DateTime.Now.AddMonths(-3);
            var endDate = DateTime.Now.AddMonths(1);
            var issueList = _context.GetIssue().Where(i => i.Date >= startDate && i.Date <= endDate && i.MagazineId == magazineItem.Issue.MagazineId).OrderBy(i => i.Date).ToList();

            int start_number = issueList[0].Number;
            int AddId = 0;
            if (magazineItem.Issue.Number < start_number)
            {
                viewData.SmallerMagazineNumber = 1;
                AddId = magazineItem.Issue.Id;
            }
            viewData.IssueList = new SelectList(_context.FindIssuesByMagazineItemId(magazineItem.Issue.Id, AddId), "Id", "Number");
            return View(viewData);
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Update(MagazineItem magazineItem, Info info)
        {
            try
            {
                _service.Update(magazineItem, ControllerContext.HttpContext.User.Identity.Name);
                ModelState.Clear();
            }
            catch (RulesException ex)
            {
                ex.AddModelStateErrors(ModelState, "magazineItem");
            }

            if (ModelState.IsValid)
            {
                var confirmViewData = new ConfirmViewData();
                confirmViewData = InitConfirmViewData(_context.Authors.Single(a => a.Id == magazineItem.AuthorId), OperationType.Update, info);
                return View("Confirm", confirmViewData);
            }
            var magazine = _service.Find(magazineItem.Id);
            var viewData = InitMagazineItemViewData();
            viewData.Info = info;//InitInfo(info.powrot, info.month, info.year, info.user_id);
            viewData.MagazineItem = magazine;
            return View("Edit", viewData);
        }
        private Info InitInfo(string p, int m, int y, int u)
        {
            Info inf = new Info();
            inf.powrot = p;
            inf.month = m;
            inf.year = y;
            inf.user_id = u;
            return inf;
        }
        private MagazineItemViewData InitMagazineItemViewData()
        {
            var viewData = new MagazineItemViewData
            {
                MagazineItem = new MagazineItem(),
                AuthorList = new SelectList(_context.Authors.OrderBy(a => a.LastName).ToList(), "Id", "FullName"),
                MagazineList = new SelectList(_context.Magazines.ToList(), "Id", "NickName"),
                IssueList = new SelectList(_context.FindIssuesByMagazineId(0, 0), "Id", "Name"),
                ItemTypeList = new SelectList(_context.ItemTypes.ToList(), "Id", "Name"),
                SmallerMagazineNumber = 0,
                Info = new Info()
            };
            return viewData;
        }
        [Authorize]
        public ActionResult Delete(string id, string powrot, string month, string year, string user_id)
        {
            int id1 = 0;
            try
            {
                id1 = (id != null) ? Convert.ToInt32(id) : 0;
            }
            catch
            {
            }
            var deleteViewData = new DeleteViewData();            
            int month1 = (month != null) ? Convert.ToInt32(month) : 0;
            int year1 = (year != null) ? Convert.ToInt32(year) : 0;
            int user1 = (user_id != null) ? Convert.ToInt32(user_id) : 0;
            deleteViewData.Info = InitInfo(powrot, month1, year1, user1);
            return View("Delete", deleteViewData);
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(MagazineItem magazineItem, Info info)
        {
            var magazineItemToDelete = _service.Delete(magazineItem);
            var confirmViewData = new ConfirmViewData();
            if (magazineItemToDelete == null)
            {
                confirmViewData = InitConfirmViewData(null, OperationType.WrongId, info);
            }
            else
            {
                confirmViewData = InitConfirmViewData(magazineItemToDelete.Author, OperationType.Delete, info);
            }
            return View("Confirm", confirmViewData);
        }
        private ConfirmViewData InitConfirmViewData(Author author, OperationType c_type, Info inf)
        {
            var viewData = new ConfirmViewData
            {
                Author = author,
                akcja = c_type,
                info = inf
            };
            return viewData;
        }
    }
}
