package ru.yandex.webmaster3.viewer.http.turbo.comment;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.Value;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.comment.CmntIntegraionService;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.turbo.dao.TurboCmntStatisticsYDao;
import ru.yandex.webmaster3.storage.turbo.service.TurboRuntimeService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;

/**
 * ishalaru
 * 26.05.2020
 **/
@ReadAction
@Description("Получение общего статуса подключения Турбо для e-commerce")
@Component("/turbo/cmnt/status")
@Category("turbo")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class TurboCmntStatusAction extends AbstractUserVerifiedHostAction<TurboCmntStatusAction.Request, TurboCmntStatusAction.Response> {

    private final TurboCmntStatisticsYDao turboCmntStatisticsYdbDao2;
    private final CmntIntegraionService cmntIntegraionService;
    private final TurboRuntimeService turboRuntimeService;

    @Override
    public Response process(Request request) {
        String template = request.template == null ? "" : request.template;
        final List<TurboCmntStatisticsYDao.TurboCmntStatistics> select =
                turboCmntStatisticsYdbDao2.select(WwwUtil.cutWWWAndM(request.getHostId()),
                        request.startDate,
                        request.endDate,
                        template,
                        request.enable,
                        request.pageSize);
        final Map<String, TurboCmntStatisticsYDao.TurboCmntStatistics> urlsMap = select.stream().collect(Collectors.toMap(e -> urlCutPrefix(e.getUrl()), e -> e));
        final Map<String, Integer> cmntCount = cmntIntegraionService.loadCommentsCount(urlsMap.keySet());
        final Map<String, String> turboUrlsMap = turboRuntimeService.loadTurboUrls(urlsMap.values().stream().map(e -> e.getUrl()).collect(Collectors.toList()));

        final List<ResponseModel> collect = urlsMap.entrySet().stream().map(e ->
                new ResponseModel(e.getValue().getUrl(),
                        e.getValue().getTitle(), e.getValue().isEnable(), e.getValue().getStartDate(),
                        cmntCount.get(e.getKey()), turboUrlsMap.get(e.getValue().getUrl()))
        ).collect(Collectors.toList());
        return new Response(collect);
    }

    public LocalDate convert(java.time.LocalDate date) {
        return new LocalDate(date.getYear(), date.getMonthValue(), date.getDayOfMonth());
    }

    public String urlCutPrefix(String url) {
        if (url.startsWith("https://")) {
            return url.substring(8);
        }
        return url.substring(7);
    }

    @Data
    public static final class Request extends AbstractUserVerifiedHostRequest {
        @Setter(onMethod_ = {@Description("Размер страницы"), @RequestQueryProperty(required = true)})
        int pageSize;
        @Setter(onMethod_ = {@Description("Время начала периода"), @RequestQueryProperty(required = true)})
        LocalDate startDate;
        @Setter(onMethod_ = {@Description("Время конца периода"), @RequestQueryProperty(required = true)})
        LocalDate endDate;
        @Setter(onMethod_ = {@Description("Шаблон текста для поиска"), @RequestQueryProperty(required = false)})
        String template;
        @Setter(onMethod_ = {@Description("Статус подключения комментариев"), @RequestQueryProperty(required = false)})
        Boolean enable;
    }

    @Value
    public static final class Response implements ActionResponse.NormalResponse {
        List<ResponseModel> list;
    }

    @Value
    public static final class ResponseModel {
        String url;
        String title;
        boolean enable;
        LocalDate startDate;
        int count;
        String turboUrl;
    }
}
