package ru.yandex.webmaster3.viewer.http.nca;

import java.util.Date;
import java.util.List;
import java.util.Map;

import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.Action;
import ru.yandex.webmaster3.core.http.ActionRequest;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.http.request.PagerAware;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.core.util.PageUtils;
import ru.yandex.webmaster3.storage.nca.CtlogCertificatesCHDao;
import ru.yandex.webmaster3.storage.nca.NcaRulesService;
import ru.yandex.webmaster3.storage.nca.data.ParsedCertificateState;


/**
 * @author kravchenko99
 * @date 3/23/22
 */

@Slf4j
@Component("/nca/ctlog/check/certificates")
@WriteAction
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Category("nca")
public class CheckNcaCertificatesByCTLogAction extends Action<CheckNcaCertificatesByCTLogAction.Req, CheckNcaCertificatesByCTLogAction.Res> {

    private final CtlogCertificatesCHDao ctlogCertificatesCHDao;
    private final NcaRulesService ncaRulesService;

    @Override
    public Res process(Req request) throws WebmasterException {
        String requestDomain;

        try {
            requestDomain = IdUtils.urlToHostId(request.domain).getPunycodeHostname();
        } catch (Exception ignored) {
            return new Res(List.of(), 0);
        }

        CtlogCertificatesCHDao.PageWithCertificatesAndCount certificates =
                ctlogCertificatesCHDao.getCertificates(requestDomain, request.getPager());

        List<ParsedCertificateState> parsedCertificateStates = certificates.certificateStates();
        long certificatesCount = certificates.count();

        Map<String, DateTime> rulesForDomain = ncaRulesService.getRulesForDomain(requestDomain);

        certificatesCount += rulesForDomain.size();


        for (var entry : rulesForDomain.entrySet()) {
            if (parsedCertificateStates.size() >= request.pageSize) {
                break;
            }

            String key = entry.getKey();
            DateTime value = entry.getValue();

            parsedCertificateStates.add(ParsedCertificateState.builder()
                    .domains(List.of(key))
                    .notBefore(new Date(value.getMillis()))
                    .notAfter(new Date(value.plusYears(1).getMillis()))
                    .build());
        }

        return new Res(parsedCertificateStates, certificatesCount);
    }

    @Setter(onMethod_ = @RequestQueryProperty(required = true))
    public static class Req implements ActionRequest, PagerAware {
        String domain;
        private int page;
        private int pageSize;

        @Override
        public void setP(int page) {
            this.page = page;
        }

        @Override
        public void setPSize(int pageSize) {
            this.pageSize = pageSize;
        }

        public PageUtils.Pager getPager() {
            return PageUtils.getPage(page, pageSize);
        }
    }

    @Value
    public static class Res implements ActionResponse.NormalResponse  {
        List<ParsedCertificateState> parsedCertificates;
        long certificateCount;
    }
}
