package ru.yandex.webmaster3.viewer.http.searchquery.rivals;

import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import org.joda.time.format.DateTimeFormat;
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.searchquery.DownloadRivalsStatisticsTaskData;
import ru.yandex.webmaster3.viewer.http.download.DownloadAction;

/**
 * Created by Oleg Bazdyrev
 */
@ReadAction
@Description("Выгрузка статистики по конкурентам")
@Category("searchquery")
public class DownloadRivalsStatisticsAction extends DownloadAction<DownloadRivalsStatisticsRequest> {

    @Override
    protected WorkerTaskData getTaskData(DownloadRivalsStatisticsRequest request, long hash) {
        String fileName = generateFileName(request, hash);
        return new DownloadRivalsStatisticsTaskData(
                request.getHostId(),
                request.getDateFrom().toLocalDate(),
                request.getDateTo().toLocalDate(),
                request.getDeviceType(),
                request.getExportFormat(),
                fileName,
                hash,
                request.getPeriod(),
                request.getThematics());
    }

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

        Hasher hc = hf.newHasher()
                .putInt(request.getHostId().hashCode())
                .putString(request.getExportFormat().toString(), Charsets.UTF_8)
                .putString(request.getDateFrom().toString(DateTimeFormat.shortDate()), Charsets.UTF_8)
                .putString(request.getDateTo().toString(DateTimeFormat.shortDate()), Charsets.UTF_8)
                .putInt(request.getDeviceType().value())
                .putInt(request.getPeriod().value())
                .putString(request.getThematics(), Charsets.UTF_8);

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

}

