package ru.yandex.webmaster3.storage.download;

import org.joda.time.Duration;
import org.joda.time.Instant;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
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 ifilippov5 on 08.02.17.
 */
@Repository
public class DownloadInfoYDao extends AbstractYDao {

    private static final String INDEX_FILE_NAME = "file_name_idx";
    private static final Duration TTL = Duration.standardHours(1);

    public DownloadInfoYDao() {
        super(PREFIX_WEBMASTER3, "download_info");
    }

    public void add(WebmasterHostId hostId, long downloadId, DownloadInfo downloadInfo) {
        upsert(
                F.HOST_ID.value(hostId),
                F.DOWNLOAD_ID.value(downloadId),
                F.STATUS.value(downloadInfo.getDownloadStatus()),
                F.URL.value(downloadInfo.getPublicUrlMds()),
                F.FILE_NAME.value(downloadInfo.getFileName()),
                F.UPDATE_DATE.value(Instant.now())
        ).execute();
    }

    public DownloadInfo get(WebmasterHostId hostId, long downloadId) {
        Instant nowMinusTtl = Instant.now().minus(TTL);
        // фильтруем так как у ydb кривые ttl
        return select(MAPPER)
                .where(F.DOWNLOAD_ID.eq(downloadId))
                .and(F.HOST_ID.eq(hostId))
                .and(F.UPDATE_DATE.gt(nowMinusTtl))
                .queryOne();
    }

    public DownloadInfo searchByFileName(String fileName) {
        return select(MAPPER).secondaryIndex(INDEX_FILE_NAME).where(F.FILE_NAME.eq(fileName)).queryOne();
    }

    public static final DataMapper<DownloadInfo> MAPPER = DataMapper.create(
            F.STATUS, F.URL, F.FILE_NAME,
            DownloadInfo::new
    );

    private static class F {
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        static final Field<Long> DOWNLOAD_ID = Fields.longField("download_id");
        static final Field<DownloadStatus> STATUS = Fields.intEnumField("download_status", DownloadStatus.R);
        static final Field<String> URL = Fields.stringField("public_url_mds").makeOptional();
        static final Field<String> FILE_NAME = Fields.stringField("file_name").makeOptional();
        static final Field<Instant> UPDATE_DATE = Fields.jodaInstantField("update_date");
    }
}
