using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ResourcesManager.Models;
using System.Web.Helpers;
using System.IO;

namespace ResourcesManager.Controllers
{
    [Authorize]
    public class NotificationsController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public ActionResult Readed(int? id, string link = null)
        {
            try
            {
                if (id == null)
                {
                    logger.Warn("BadRequest");
                
                }
                db.Notifications.First(n => n.Id == id).Readed = true;
                db.SaveChanges();
                if (string.IsNullOrEmpty(link) || link == "null")
                {
                    return Redirect(Request.UrlReferrer.ToString());
                }
            }
            catch (Exception ex)
            {
                logger.Error("", ex);
            }
            return Redirect(link);

        }

        public ActionResult GetUnread()
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                try
                {
                    return Json(db.Notifications.OrderByDescending(k => k.CreateDate).Where(m => m.Readed == false && (m.User == User.Identity.Name || m.User == null)).ToList(), JsonRequestBehavior.AllowGet);
                }
                catch (Exception e)
                {
                    logger.Warn("hiba", e);
                    return null;
                }
            }
        }
        public ActionResult MakeReadAll()
        {
            try
            {
                db.Notifications.Where(k => k.Readed == false && (k.User == User.Identity.Name || k.User == null)).ToList().ForEach(k => k.Readed = true);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                logger.Error("", ex);
            }
            return Redirect(HttpContext.Request.UrlReferrer.ToString());
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
