package ru.yandex.webmaster3.worker.digest;


import lombok.AllArgsConstructor;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.notification.LanguageEnum;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.storage.digest.DigestMessage;
import ru.yandex.webmaster3.storage.digest.DigestMessagesCHDao;
import ru.yandex.webmaster3.storage.user.notification.NotificationType;
import ru.yandex.webmaster3.storage.util.clickhouse2.ClickhouseException;

@Service
@AllArgsConstructor(onConstructor_ = @Autowired)
public class DigestDevSenderService {
    @Value("${webmaster3.worker.digest.templateHosts}")
    private final String[] templateHosts;
    @Value("${webmaster3.worker.digest.acceptEmails}")
    private final String[] devEmails;
    private DigestNotificationService digestNotificationService;
    private DigestMessagesCHDao digestMessagesCHDao;

    public boolean sendDigest(String email, LanguageEnum lang, NotificationType notificationType,  LocalDate date, WebmasterHostId hostId){
        try {
            DigestMessage message = digestMessagesCHDao.getMessagesForHost(date, hostId).stream().findAny().orElse(null);
            if (message != null) {
                if (lang != null) {
                    message = new DigestMessage(message.getUserId(), message.getHostId(), message.getEmail(), lang, notificationType, message.getDigest(), message.getDigestPeriodEnd());
                }

                return digestNotificationService.sendDigest(message, email);
            }
        } catch (ClickhouseException e) {
            throw new RuntimeException(e);
        }

        return false;
    }

    public void sendEmailsToApprove(LocalDate date) {
        for (String email : devEmails) {
            for (String host : templateHosts) {
                sendDigest(email, LanguageEnum.RU, NotificationType.DIGEST, date, IdUtils.stringToHostId(host));
                sendDigest(email, LanguageEnum.RU, NotificationType.DIGEST_LITE, date, IdUtils.stringToHostId(host));
            }
        }
    }

}
