package cn.reghao.tnb.message.app.service;

import cn.reghao.jutil.jdk.thread.ThreadPoolWrapper;
import cn.reghao.tnb.common.util.ConstantId;
import cn.reghao.tnb.message.api.constant.MsgType;
import cn.reghao.tnb.message.api.dto.UserMessageDto;
import cn.reghao.tnb.message.app.service.notifier.Notify;
import cn.reghao.tnb.message.app.service.notifier.ding.DingMsg;
import cn.reghao.tnb.message.app.service.notifier.ding.DingNotify;
import cn.reghao.tnb.message.app.service.notifier.email.EmailMsg;
import cn.reghao.tnb.message.app.service.notifier.email.EmailNotify;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;

/**
 * 通知服务
 *
 * @author reghao
 * @date 2021-02-25 00:10:17
 */
@Slf4j
@Service
public class NotifyService {
    private final ExecutorService threadPool = ThreadPoolWrapper.threadPool("notify-service");
    private final DingNotify dingNotify;
    private final EmailNotify emailNotify;
    private final UserMessageService userMessageService;

    public NotifyService(DingNotify dingNotify, EmailNotify emailNotify,
                         UserMessageService userMessageService) {
        this.dingNotify = dingNotify;
        this.emailNotify = emailNotify;
        this.userMessageService = userMessageService;
    }

    public <T> void notify(String receiver, T msg) {
        if (msg instanceof DingMsg) {
            DingMsg dingMsg = (DingMsg) msg;
            threadPool.execute(new NotifyTask<>(dingNotify, receiver, dingMsg, userMessageService));
        } else if (msg instanceof EmailMsg) {
            EmailMsg emailMsg = (EmailMsg) msg;
            threadPool.execute(new NotifyTask<>(emailNotify, receiver, emailMsg, userMessageService));
        }
    }
    /**
     * @param
     * @return
     * @date 2021-06-23 上午9:29
     */
    static class NotifyTask<T> implements Runnable {
        private final Notify<T> notify;
        private final String receiver;
        private final T msg;
        private final UserMessageService userMessageService;

        public NotifyTask(Notify<T> notify, String receiver, T msg, UserMessageService userMessageService) {
            this.notify = notify;
            this.receiver = receiver;
            this.msg = msg;
            this.userMessageService = userMessageService;
        }

        @Override
        public void run() {
            try {
                notify.send(receiver, msg);
            } catch (Exception e) {
                int msgType = MsgType.sysMsg.getValue();
                String title = "发送通知失败";
                String content = String.format("发送给 %s 的通知失败 -> %s", receiver, e.getMessage());
                UserMessageDto userMessageDto = new UserMessageDto(msgType, title, content, ConstantId.ANONYMOUS_USER_ID);
                userMessageService.addMessage(userMessageDto);
            }
        }
    }
}
