package ru.yandex.webmaster3.storage.tools;

import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

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

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;

/**
 * @author vsedaikina
 * 21.02.22
 *
 * TTL 1 день по полю add_date
 */
@Repository
public class ToolsRequestsPerUserYDao extends AbstractYDao {
    public static final Duration TTL = Duration.standardDays(1);

    private ToolsRequestsPerUserYDao() {
        super(PREFIX_TOOLS, "tools_requests_per_user");
    }

    public void insert(long userId, UUID requestId, DateTime addDate, String requestUrl, ToolType toolType) {
        upsert(
                F.USER_ID.value(userId),
                F.REQUEST_ID.value(requestId),
                F.ADD_DATE.value(addDate),
                F.REQUEST_URL.value(requestUrl),
                F.TOOL_TYPE.value(toolType)
        ).execute();
    }

    public void deleteForUser(long userId) {
        delete().where(F.USER_ID.eq(userId)).execute();
    }

    public List<ToolsRequestInfo> getAllHostRequestsByCreationDesc(long userId, DateTime fromDate, ToolType toolType) {
        var reqs = select(MAPPER)
                .where(F.USER_ID.eq(userId))
                .and(F.TOOL_TYPE.eq(toolType))
                .queryForList();

        return reqs.stream()
                .filter(r -> r.getAddDate().isEqual(fromDate) || r.getAddDate().isAfter(fromDate))
                .sorted(Comparator.comparing(ToolsRequestInfo::getAddDate).reversed())
                .collect(Collectors.toList());
    }

    private static final DataMapper<ToolsRequestInfo> MAPPER = DataMapper.create(
            F.USER_ID,
            F.REQUEST_ID,
            F.ADD_DATE,
            F.REQUEST_URL,
            F.TOOL_TYPE,
            (userId, requestId, addDate, requestUrl, toolType) -> ToolsRequestInfo.builder().userId(userId)
                    .requestId(requestId).addDate(addDate).requestUrl(requestUrl).toolType(toolType).build()
    );

    private interface F {
        Field<Long> USER_ID = Fields.longField("user_id");
        Field<UUID> REQUEST_ID = Fields.uuidField("request_id");
        Field<DateTime> ADD_DATE = Fields.jodaDateTimeField("add_date");
        Field<String> REQUEST_URL = Fields.stringField("request_url");
        Field<ToolType> TOOL_TYPE = Fields.stringEnumField("tool_type", ToolType.R);
    }
}
