package me.qwq.doghouse.entity.config;

import java.io.Serializable;
import java.time.Duration;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;

import lombok.Data;
import lombok.experimental.Accessors;
import me.qwq.doghouse.annotation.ConfigInfo;
import me.qwq.doghouse.constants.UsefulRegex;
import me.qwq.doghouse.interfaces.IConfig;
import me.qwq.doghouse.service.MailService;
import me.qwq.doghouse.util.SpringContextHolder;

@SuppressWarnings("serial")
@Data
@Accessors(chain=true)
@ConfigInfo(field="mail", name="邮件设置", initDefault=true)
public class MailConfig implements Serializable, IConfig<MailConfig> {
    
    private static final Boolean DEFAULT_MAIL_ON = false;
    private static final String EMPTY_STRING = "";
    private static final String DEFAULT_SUBJECT = "您在 Doghouse 的留言有新回复啦";
    

    @NotBlank
    private boolean mailOn = DEFAULT_MAIL_ON;
    
    @NotBlank
    private String username = EMPTY_STRING;
    
    private String password = EMPTY_STRING;
    
    @NotBlank
    @Pattern(regexp = UsefulRegex.DOMAIN_WITHOUT_SCHEME)
    private String smtpHost = EMPTY_STRING;
    
    @NotNull
    @Size(min=1, max=65535)
    private Integer smtpPort = 25;
    
    @NotBlank
    private String subject = DEFAULT_SUBJECT;
    
    @NotBlank
    @Pattern(regexp = UsefulRegex.EMAIL)
    private String fromAddress = EMPTY_STRING;
    
    private String fromUser = EMPTY_STRING;
    
    @NotBlank
    @Pattern(regexp = UsefulRegex.EMAIL)
    private String adminAddress = EMPTY_STRING;

    private boolean tlsEnable = false;
    
    @NotNull
    @Size(min = 0, max = 1440)
    private Long sendingDelay = 5L;
    
    /**
     * 获取用于 Redisson 过期的 Duration
     * @return
     */
    public Duration getMailDuration() {
        if (sendingDelay == null || sendingDelay <= 0L) {
            return Duration.ofSeconds(1L);
        }
        return Duration.ofMinutes(sendingDelay);
    }
    
    @Override
    public MailConfig afterSaving() {
        SpringContextHolder.getBean(MailService.class).resetTaskDelay();
        return this;
    }
    
}
