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

import com.google.common.base.Charsets;
import com.google.common.hash.Funnel;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.worker.task.WorkerTaskData;
import ru.yandex.webmaster3.storage.download.urls.DownloadSearchUrlsTaskData;
import ru.yandex.webmaster3.storage.searchurl.SearchUrlFilter;
import ru.yandex.webmaster3.storage.searchurl.SearchUrlSamplesService;
import ru.yandex.webmaster3.viewer.http.download.DownloadAction;

/**
 * Created by ifilippov5 on 30.01.17.
 */
@ReadAction
@Description("Выгрузка страниц в поиске")
@Category("searchurl")
public class DownloadSearchUrlsAction extends DownloadAction<DownloadSearchUrlsRequest> {
    private SearchUrlSamplesService searchUrlSamplesService;

    @Override
    protected WorkerTaskData getTaskData(DownloadSearchUrlsRequest request, long hash) {
        String fileName = generateFileName(request, hash);
        return DownloadSearchUrlsTaskData.createTaskData(
                request.getHostId(),
                request.getParameterFilters(),
                request.getNodeId(),
                request.getExportFormat(),
                fileName,
                hash
        );
    }

    @Override
    protected long getHash(DownloadSearchUrlsRequest request) {
        HashFunction hf = Hashing.md5();

        Hasher hc = hf.newHasher()
                .putInt(request.getHostId().hashCode())
                .putString(request.getExportFormat().toString(), Charsets.UTF_8)
                .putString(searchUrlSamplesService.getUrlSamplesDataVersion(request.getHostId()), Charsets.UTF_8);

        if (request.getNodeId() != null)
            hc.putLong(request.getNodeId());

        if (request.getParameterFilters() != null) {
            for (SearchUrlFilter filter : request.getParameterFilters()) {
                hc.putObject(filter, (Funnel<SearchUrlFilter>) (searchUrlFilter, into) -> {
                    into.putString(searchUrlFilter.getOperation().toString(), Charsets.UTF_8);
                    into.putString(searchUrlFilter.getIndicator().toString(), Charsets.UTF_8);
                    into.putString(searchUrlFilter.getValue(), Charsets.UTF_8);
                });
            }
        }

        return hc.hash().asLong();
    }

    @Required
    public void setSearchUrlSamplesService(SearchUrlSamplesService searchUrlSamplesService) {
        this.searchUrlSamplesService = searchUrlSamplesService;
    }
}
