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

import java.util.List;
import java.util.function.Consumer;

import com.fasterxml.jackson.core.type.TypeReference;
import lombok.Value;
import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.storage.user.CustomizableSurveyTypeEnum;
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;

/**
 * ishalaru
 * 23.12.2020
 **/
@Repository
public class DashboardSurveyAnswersYDao extends AbstractYDao {
    public DashboardSurveyAnswersYDao() {
        super(PREFIX_USER, "dashboard_survey_answers");
    }

    public void add(Long userId, WebmasterHostId hostId, String surveyType, CustomizableSurveyTypeEnum answerPlace,
                    List<String> selectedCases) {
        add(userId, hostId, surveyType, answerPlace == null ? "" : answerPlace.toString(), selectedCases);
    }

    public void add(Long userId, WebmasterHostId hostId, String surveyType, String answerPlace,
                    List<String> selectedCases) {
        upsert(F.USER_ID.value(userId),
                F.HOST_ID.value(hostId),
                F.ANSWER_PLACE.value(answerPlace),
                F.SURVEY_TYPE.value(surveyType),
                F.CASES.value(selectedCases),
                F.UPDATED.value(DateTime.now())).execute();
    }

    public boolean contains(WebmasterHostId hostId, String surveyType) {
        return select(F.HOST_ID)
                .where(F.HOST_ID.eq(hostId))
                .and(F.SURVEY_TYPE.eq(surveyType))
                .limit(1)
                .queryOne() != null;
    }

    public void scan(Consumer<UserCase> consumer) {
        streamReader(MAPPER, consumer);
    }

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

    private final static DataMapper<UserCase> MAPPER = DataMapper.create(
            F.USER_ID, F.HOST_ID, F.SURVEY_TYPE, F.ANSWER_PLACE, F.UPDATED, F.CASES,
            UserCase::new
    );

    @Value
    public static class UserCase {
        Long userId;
        WebmasterHostId hostId;
        String surveyType;
        String answerPlace;
        DateTime updated;
        List<String> cases;
    }

    interface F {
        Field<Long> USER_ID = Fields.longField("user_id");
        Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id").makeOptional();
        Field<String> SURVEY_TYPE = Fields.stringField("survey_type");
        Field<String> ANSWER_PLACE = Fields.stringField("answer_place");
        Field<DateTime> UPDATED = Fields.jodaDateTimeField("updated");
        Field<List<String>> CASES = Fields.jsonField("cases", new TypeReference<>() {
        });
    }

}
