package cn.reghao.devops.mgr.admin.service;

import cn.reghao.devops.mgr.admin.db.repository.WebhookRepository;
import cn.reghao.devops.mgr.admin.service.notifier.ding.DingMsg;
import cn.reghao.devops.mgr.admin.service.notifier.ding.DingNotify;
import cn.reghao.devops.mgr.admin.model.vo.NotifyType;
import cn.reghao.devops.mgr.admin.model.po.Webhook;
import cn.reghao.devops.mgr.admin.service.notifier.Notify;
import cn.reghao.jutil.jdk.thread.ThreadPoolWrapper;
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 WebhookRepository webhookRepository;
    private final SysMessageService sysMessageService;

    public NotifyService(DingNotify dingNotify, WebhookRepository webhookRepository, SysMessageService sysMessageService) {
        this.dingNotify = dingNotify;
        this.webhookRepository = webhookRepository;
        this.sysMessageService = sysMessageService;
    }

    public <T> void notify(T msg) {
        String receiver;
        if (msg instanceof DingMsg) {
            Webhook webhook = webhookRepository.findByTypeAndSetdefaultIsTrue(NotifyType.webhook.getName());
            if (webhook != null) {
                receiver = webhook.getUrl();
                DingMsg dingMsg = (DingMsg) msg;
                threadPool.execute(new NotifyTask<>(sysMessageService, dingNotify, receiver, dingMsg));
            }
        }
    }

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

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

        @Override
        public void run() {
            try {
                notify.send(receiver, msg);
            } catch (Exception e) {
                String title = "发送通知失败";
                String content = String.format("发送给 %s 的通知失败 -> %s", receiver, e.getMessage());
                sysMessageService.putSysMessage(title, content);
            }
        }
    }
}
