package ru.yandex.webmaster3.storage.radar;

import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.notification.LanguageEnum;
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;

@Repository
public class RadarThematicsYDao extends AbstractYDao {

    private static final String TABLE_NAME = "radar_thematics";

    protected RadarThematicsYDao() {
        super(PREFIX_WEBMASTER3, TABLE_NAME);
    }

    public void insert(RadarThematics rt) {
        upsert(F.PARENT_ID.value(rt.getParentId()),
                F.ID.value(rt.getId()),
                F.NAMES.value(rt.getNames()),
                F.VISIBLE.value(rt.isVisible()))
                .execute();
    }

    public void delete(RadarThematics rt) {
        delete()
                .where(F.PARENT_ID.eq(rt.getParentId()))
                .and(F.ID.eq(rt.getId()))
                .execute();
    }

    public List<RadarThematics> listAll() {
        return select(MAPPER).queryForList();
    }

    private final static DataMapper<RadarThematics> MAPPER = DataMapper.create(
            F.PARENT_ID, F.ID, F.NAMES, F.VISIBLE, RadarThematics::new
    );

    private interface F {
        TypeReference<Map<LanguageEnum, String>> MAP = new TypeReference<>() {
        };

        Field<String> PARENT_ID = Fields.stringField("parent_id");
        Field<String> ID = Fields.stringField("id");
        Field<Map<LanguageEnum, String>> NAMES = Fields.mapField("names", MAP);
        Field<Boolean> VISIBLE = Fields.boolField("visible");
    }
}
