using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Wierszowki.Core.Interfaces;
using Wierszowki.Core.Linq;
using Wierszowki.Models;
using System.Globalization;

namespace Wierszowki.Controllers
{
    [Authorize]
    [HandleError]
    public class ReportController : Controller
    {
        private readonly IRepository<MagazineItem> _repository;

        private readonly WierszowkiDataContext _context;

        public ReportController()
        {
            _context = new WierszowkiDataContext();
            _repository = new LinqRepository<MagazineItem>();
        }

        public ReportController(IRepository<MagazineItem> repository, WierszowkiDataContext dataContext)
        {
            _repository = repository;
            _context = dataContext;
        }

        public ActionResult Index()
        {

            var viewData = new ReportViewData
            {
                Authors = _context.GetAuthors().OrderBy(a => a.FullName).ToList(),
                EmploymentTypeList =  new SelectList(_context.GetEmploymentTypes().ToList(),"Id","Name"),
                UserList = new SelectList(_context.GetUsers().OrderBy(u => u.FullName).ToList(),"Id","FullName")
            };
            return View(viewData);
        }

        public ActionResult All(int year, int month, int user)
        {
            var allViewData = new AllViewData();
            string error = "";
            string naglowek = "";
            
            if (user <= 0)
            {
                error = "Nie można wyświetlić wierszówek. Spróbuj jeszcze raz. ";
                allViewData = InitAllViewData("", error, null, null);
                return View("Error",allViewData);
            }
            var name = "";
            var items = new List<MagazineItem>();
            if (user > 0)
            {
                var u = _context.GetUserById(user);
                if (u != null)
                {
                    name = u.FullName;
                    items = _repository.Find(m => m.Date.Month == month && m.Date.Year == year && m.CreatedBy == user)
                                   .OrderByDescending(m => m.UpdatedOn).ToList();

                    if (items.Count <= 0)
                    {
                        error = "Brak wierszówek dla tego użytkownika.";
                        allViewData = InitAllViewData("", error, null, null);
                        return View("Error", allViewData);
                    }
                }
                else
                {
                    //Użytkownik bo taki nie istnieje 
                    error = "Nie można wyswietlić wierszówek, gdyż użytkownik nie istnieje. ";
                    allViewData = InitAllViewData("", error, null, null);
                    return View("Error", allViewData);   
                }
                DateTime dat = new DateTime(1, 1, 1);
                dat = dat.AddYears(year-1);
                dat = dat.AddMonths(month-1);
               
                naglowek = "<div class='st1'>Wierszówki z " + dat.ToString("MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")) + "</div>";
                if ( name != "")
                {
                    naglowek += "<div class='st1'>Wprowadzający: <span>" + name + "</span></div>";
                }
            }
            Info inf = new Info();
            inf.powrot = "2";
            inf.month = month;
            inf.year = year;
            inf.user_id = user;

            allViewData = InitAllViewData(naglowek, error, inf, items);
            return View("All", allViewData); 
        }

        public ActionResult ToPrice()
        {
            string naglowek = "Wierszówki do wyceny";
            string  error = "";
            var allViewData = new AllViewData();
            Info inf = new Info();
            inf.powrot = "1";
            var items = _repository.Find(m => m.Price <= 0).ToList();
            if ( items.Count <= 0  )
            {
                error = "Brak wierszówek do wyceny.";
                allViewData = InitAllViewData(naglowek, error, null, null);
                return View("Error", allViewData);  
            }
            allViewData = InitAllViewData(naglowek, "", inf, items);
            return View("All", allViewData);
        }

        public ActionResult Show(int year, int month, int employment)
        {
            var magazineItems = _context.FindItemsByYearMonthAndEmploymentType(year, month, employment);
            return View(magazineItems);
        }

        public ActionResult AuthorCard(int year, int month, int author)
        {
            var magazineItems = _context.FindItemsByYearMonthAndAuthor(year, month, author);
            if (magazineItems.Count() <= 0)
                return RedirectToAction("AuthorCardNotFound", _context.Authors.SingleOrDefault(a => a.Id == author));
            
            var viewData = new AuthorCardViewData
            {
                FullName = magazineItems[0].Author.FullName,
                Date = magazineItems[0].Date,
                MagazineItems = new Dictionary<string, List<MagazineItem>>()
            };
            foreach (var magazineItem in magazineItems)
            {
                var key = magazineItem.Issue.Magazine.NickName;
                if (!viewData.MagazineItems.ContainsKey(key))
                {
                    viewData.MagazineItems[key] = new List<MagazineItem>();
                }
                viewData.MagazineItems[key].Add(magazineItem);
                viewData.Price += magazineItem.Price;
                viewData.Bonus += magazineItem.Bonus;
                viewData.Total += magazineItem.Price + magazineItem.Bonus;
            }
            return View(viewData);
        }

        public ActionResult AuthorCardNotFound(Author author)
        {
            return View(author);
        }

        public ActionResult Authors(int year, int month)
        {
            ViewData["ReportDate"] = new DateTime(year, month, 1);
            var reports = _context.GetAuthorsReport(year, month);
            return View(reports);
        }

        public ActionResult AuthorsByMagazines(int year, int month)
        {
            var viewData = new ReportViewData();
            viewData.ReportDate = new DateTime(year, month, 1);
            viewData.Authors = _context.GetAuthors();
            viewData.Magazines = _context.GetMagazines();
            viewData.ReportData = _context.GetAuthorsByMagzinesReport(year, month, viewData.Authors, viewData.Magazines);
            return View(viewData);
        }

        public ActionResult AuthorsByMagazinesByEmployment(int year, int month, int? employment)
        {
            var employmentId = employment.HasValue ? employment.Value : 1;

            var viewData = new ReportViewData();
            viewData.ReportDate = new DateTime(year, month, 1);
            viewData.Employment = _context.EmploymentTypes.SingleOrDefault(e => e.Id == employmentId);
            viewData.Authors = _context.GetAuthors().Where(a => a.EmploymentType == viewData.Employment).ToList();
            viewData.Magazines = _context.GetMagazines();
            viewData.ReportData = _context.GetAuthorsByMagzinesReport(year, month, viewData.Authors, viewData.Magazines);
            return View("AuthorsByMagazines", viewData);
        }
        private AllViewData InitAllViewData(string str, string er, Info inf, List<MagazineItem> list)
        {
            var viewData = new AllViewData
            {
                naglowek = str,
                error = er,
                info = inf,
                magazine = list
            };
            return viewData;
        }  
    }
}