package com.arms.api.util.aspect;

import com.arms.api.util.slack.SlackNotificationService;
import com.arms.api.util.slack.SlackProperty;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class SlackSendAdvice {

    private final SlackNotificationService slackNotificationService;

    @Before("@annotation(slackSendAlarm)")
    public void beforeMethod(JoinPoint joinPoint, SlackSendAlarm slackSendAlarm) {
        try{
            if(!ObjectUtils.isEmpty(slackSendAlarm.messageOnStart())){
                slackNotificationService.sendMessageToChannel(SlackProperty.Channel.engine,slackSendAlarm.messageOnStart());
            }
        }catch (RuntimeException e){
            log.error(e.getMessage());
        }
    }

    @AfterReturning("@annotation(slackSendAlarm)")
    public void afterReturning(JoinPoint joinPoint, SlackSendAlarm slackSendAlarm) {
        try{
            if(!ObjectUtils.isEmpty(slackSendAlarm.messageOnEnd())){
                slackNotificationService.sendMessageToChannel(SlackProperty.Channel.engine,slackSendAlarm.messageOnEnd());
            }
        }catch (RuntimeException e){
            log.error(e.getMessage());
        }
    }

    @AfterThrowing(value = "@annotation(slackSendAlarm)",throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, SlackSendAlarm slackSendAlarm, Exception e) {
        try{
            slackNotificationService.sendMessageToChannel(SlackProperty.Channel.engine,e.getMessage());
        }catch (Exception ex){
            log.error(ex.getMessage());
        }
    }
}
