package ru.yandex.webmaster3.worker.fresh;

import java.io.IOException;
import java.util.UUID;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Range;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.worker.task.PeriodicTaskState;
import ru.yandex.webmaster3.core.worker.task.PeriodicTaskType;
import ru.yandex.webmaster3.storage.searchbase.dao.MonsterHostsYDao;
import ru.yandex.webmaster3.storage.util.yt.AsyncTableReader;
import ru.yandex.webmaster3.storage.util.yt.YtPath;
import ru.yandex.webmaster3.storage.util.yt.YtService;
import ru.yandex.webmaster3.storage.util.yt.YtTableReadDriver;
import ru.yandex.webmaster3.worker.PeriodicTask;
import ru.yandex.webmaster3.worker.TaskSchedule;

/**
 * ishalaru
 * 18.03.2021
 **/
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ImportMonstersHostsPeriodicTask extends PeriodicTask<PeriodicTaskState> {
    private final YtService ytService;
    private final MonsterHostsYDao monsterHostsYDao;
    @Value("${webmaster3.worker.monsters.table.dir}")
    private YtPath path;

    @Override
    public Result run(UUID runId) throws Exception {
        ytService.withoutTransaction(cypressService -> {
            AsyncTableReader<YtRow> tableReader =
                    new AsyncTableReader<>(cypressService, path, Range.all(),
                            YtTableReadDriver
                                    .createYSONDriver(YtRow.class))
                            .splitInParts(250000)
                            .withThreadName("monsters-import-reader");
            try (AsyncTableReader.TableIterator<YtRow> iterator = tableReader.read()) {
                while (iterator.hasNext()) {
                    final YtRow next = iterator.next();
                    monsterHostsYDao.insert(next.host);
                }
            } catch (IOException e) {
                throw new WebmasterException("YT error",
                        new WebmasterErrorResponse.YTServiceErrorResponse(getClass(), e), e);
            }
            return true;

        });
        return Result.SUCCESS;
    }

    @lombok.Value
    @RequiredArgsConstructor(onConstructor_ = @JsonCreator)
    private static class YtRow {
        @JsonProperty("key")
        String host;
    }

    @Override
    public PeriodicTaskType getType() {
        return PeriodicTaskType.IMPORT_MONSTER_HOSTS;
    }

    @Override
    public TaskSchedule getSchedule() {
        return TaskSchedule.startByCron("0 0 0 * * *");
    }

}
