package ru.yandex.webmaster3.viewer.http.download.links;

import com.google.common.hash.Hasher;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.download.common.BrokenLinkSamplesMdsExportDescriptor;
import ru.yandex.webmaster3.storage.download.common.MdsExportDescriptor;
import ru.yandex.webmaster3.storage.host.CommonDataType;
import ru.yandex.webmaster3.storage.settings.dao.CommonDataStateYDao;
import ru.yandex.webmaster3.viewer.http.download.DownloadAction2;

import java.nio.charset.StandardCharsets;

/**
 * @author leonidrom
 */
@ReadAction
@Category("links")
@Component("/links/broken/download")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class DownloadBrokenLinkSamplesAction extends DownloadAction2<DownloadBrokenLinkSamplesRequest> {
    private final CommonDataStateYDao commonDataStateYDao;

    @Override
    protected MdsExportDescriptor makeRequest(DownloadBrokenLinkSamplesRequest request) {
        return new BrokenLinkSamplesMdsExportDescriptor(request.getHostId(), request.getLinkType());
    }

    @Override
    protected void customizeHash(Hasher h, DownloadBrokenLinkSamplesRequest request) {
        var lastUpdateState = commonDataStateYDao.getValue(CommonDataType.LAST_BROKEN_LINKS_UPDATE);
        long lastUpdateTS = lastUpdateState == null ? 0 : Long.parseLong(lastUpdateState.getValue());

        h.putString(request.getHostIdString(), StandardCharsets.UTF_8);
        h.putInt(request.getLinkType().ordinal());
        h.putLong(lastUpdateTS);
    }
}
