package ru.yandex.webmaster3.storage.turbo.dao;

import java.util.UUID;

import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.turbo.model.error.TurboErrorType;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedType;
import ru.yandex.webmaster3.storage.download.DownloadStatus;
import ru.yandex.webmaster3.storage.util.ydb.AbstractYDao;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.DataMapper;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Field;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Fields;

/**
 * Created by Oleg Bazdyrev on 19/04/2018.
 */
@Repository
public class TurboDownloadTasksYDao extends AbstractYDao {

    private static final String TABLE_NAME = "turbo_download_tasks";
    private static final DataMapper<TurboDownloadTask> MAPPER =
            DataMapper.create(F.TASK_ID, F.FEED_TYPE, F.STATUS, F.ERROR, F.CONTENT, TurboDownloadTask::new);

    protected TurboDownloadTasksYDao() {
        super(PREFIX_TURBO, TABLE_NAME);
    }

    public void insertTask(TurboDownloadTask task) {
        execute(
                upsert(F.TASK_ID.value(task.getTaskId()),
                        F.FEED_TYPE.value(task.getFeedType()),
                        F.STATUS.value(task.getStatus()),
                        F.ERROR.value(task.getError()),
                        F.CONTENT.value(task.getContent()),
                        F.ADD_DATE.value(DateTime.now())
                )
        );
    }

    public TurboDownloadTask getTask(UUID taskId) {
        return queryOne(select(MAPPER).where(F.TASK_ID.eq(taskId)).getStatement(), MAPPER);
    }

    private interface F {
        Field<UUID> TASK_ID = Fields.uuidField("task_id");
        Field<TurboFeedType> FEED_TYPE = Fields.stringEnumField("feed_type", TurboFeedType.R);
        Field<DownloadStatus> STATUS = Fields.stringEnumField("status", DownloadStatus.R);
        Field<TurboErrorType> ERROR = Fields.stringEnumField("error", TurboErrorType.R).makeOptional();
        Field<String> CONTENT = Fields.stringField("content").makeOptional();
        Field<DateTime> ADD_DATE = Fields.jodaDateTimeField("add_date");
    }
}
