package ru.yandex.webmaster3.worker.url.checker3.fetchers;

import NUrlChecker.Response;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import ru.yandex.webmaster3.core.url.checker3.UrlCheckRequestParams;
import ru.yandex.webmaster3.core.util.ArcUtils;
import ru.yandex.webmaster3.storage.url.checker3.data.UrlCheckDataBlock;
import ru.yandex.webmaster3.storage.url.checker3.data.UrlCheckDataBlockType;
import ru.yandex.webmaster3.storage.url.checker3.data.blocks.PageTextContentTitleDescData;
import ru.yandex.webmaster3.worker.url.checker3.AbstractUrlCheckDataBlockFetcher;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @author leonidrom
 *
 * От Роботного сервиса текстовый архив, title и description приходят одним блоком
 */
@Component
public class PageArchiveRenderOnDataFetcher extends AbstractUrlCheckDataBlockFetcher<PageTextContentTitleDescData> {
    @Override
    public PageTextContentTitleDescData doFetchBlock(DateTime searchBaseDate, UrlCheckRequestParams requestParams) throws Exception {
        return null;
    }

    @Override
    public PageTextContentTitleDescData doFetchBlock(Response.TUrlCheckResponse response) throws Exception {
        var pageArchive = response.getRotorfullArchive();

        String content = null;
        byte[] arcData = pageArchive.getArchive().toByteArray();
        if (arcData.length != 0) {
            content = StringUtils.truncate(ArcUtils.extractDocText(arcData), UrlCheckDataBlock.MAX_TEXT_LENGTH);
        }

        byte[] alternateData = pageArchive.getMobileLinkAlternate().toByteArray();
        String linkAlternate = null;
        if (alternateData.length != 0) {
            linkAlternate = new String(alternateData, StandardCharsets.UTF_8);
        }

        return new PageTextContentTitleDescData(content, pageArchive.getTitle(), pageArchive.getMetaDescription(), linkAlternate);
    }

    @Override
    public Class<PageTextContentTitleDescData> getDataBlockClass() {
        return PageTextContentTitleDescData.class;
    }

    @Override
    public @NotNull UrlCheckDataBlockType getBlockType() {
        return UrlCheckDataBlockType.ROBOT_ARCHIVE_RENDER_ON;
    }
}
