using Microsoft.AspNet.SignalR;
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace ResourcesManager.Helpers
{
    public class NotificationHelper
    {

        readonly static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static int GetCount()
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                try
                {
                    return db.Notifications.Where(m => m.Readed == false && (m.User == HttpContext.Current.User.Identity.Name || m.User == null)).Count();
                }
                catch (Exception e)
                {
                    logger.Warn("hiba", e);
                    return 0;
                }
            }
        }

        public static void Send(List<string> users, string title, string message, string img, string url)
        {
            if (string.IsNullOrEmpty(img))
            {
                img = "/Resources/GetImage?path=~/App_Data/ResourceImages/DefaultResource.png";
            }
            else
            {
                img = "/Resources/GetImage?path=" + img;
            }
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                try
                {
                    foreach (var item in users)
                    {
                        var notify = new Notification()
                        {
                            Title = title,
                            Description = message,
                            User = item,
                            CreateDate = DateTime.Now,
                            Readed = false,
                            Link = url,
                            Logo = img
                        };

                        db.Notifications.Add(notify);                   
                    }
                    db.SaveChanges();
                    //todo: null exeptionre fut
                    var id = db.Notifications.OrderByDescending(k => k.CreateDate).FirstOrDefault(k => k.User == HttpContext.Current.User.Identity.Name).Id;
                    GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>().Clients.Users(users).send(title, message, img, url, id);
                }
                catch (Exception e)
                {
                    logger.Error("Save notification message", e);
                }
            }
        }
    }
}