using System;
using System.Collections.Generic;
using Siger.ApiCommon;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;

namespace Siger.ApiTPM.Utilities
{
    public class PushHelper: IDisposable
    {
        private readonly int _projectId;
        private readonly ISigerAppMessageRepository _messageRepository;
        private readonly ISigerProjectUserRepository _userRepository;
        private readonly ISigerAppProjectConfigRepository _projectConfigRepository;
        public PushHelper(int projectId, ISigerAppMessageRepository messageRepository, ISigerProjectUserRepository userRepository
                , ISigerAppProjectConfigRepository projectConfigRepository)
        {
            _messageRepository = messageRepository;
            _userRepository = userRepository;
            _projectConfigRepository = projectConfigRepository;
            _projectId = projectId;
        }

        /// <summary>
        /// 推送消息
        /// </summary>
        /// <param name="message">消息实体</param>
        /// <param name="isPush">是否推送</param>
        /// <param name="templateId"></param>
        /// <param name="paras"></param>
        /// <returns></returns>
        public PushMessageResult Push(siger_app_project_message message, bool isPush, int templateId, Dictionary<string, string> paras)
        {
            //插入数据库
            var insertStatus = _messageRepository.InsertMessage(message);
            if (isPush)
            {
                var config = _projectConfigRepository.GetAppProjectConfig(_projectId);
                if (config != null)
                {
                    var isOnline = _userRepository.IsOnlie(message.tomid, message.projectid, SystemConfigKey.AppUserOnlineInterval);
                    var toUserKey = _userRepository.GetUserAppKey(message.tomid, message.projectid);
                    var mobile = _userRepository.GetUserMobile(message.tomid, message.projectid);
                    var pushmessage = new MessagePushHelper(config.appkey, config.appsecret, config.signid, config.issendSMS);
                    var res = pushmessage.PushMessage(message, isOnline, toUserKey, mobile, templateId, paras);
                    return res;
                }

                return PushMessageResult.ConfigMissing;
            }

            if(insertStatus > 0)
            {
                return PushMessageResult.SendSuccessful;
            }
            return PushMessageResult.PushMessageFailed;
        }
        
        public void Dispose()
        {

        }
    }
}
