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

import java.util.HashMap;
import java.util.Map;

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

import ru.yandex.webmaster3.core.checklist.data.SiteProblemTypeEnum;
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 avhaliullin
 */
@Repository
public class CleanableProblemsLastUpdateYDao extends AbstractYDao {
    public CleanableProblemsLastUpdateYDao() {

        super(PREFIX_WEBMASTER3, "cleanable_problems_last_update");
    }

    public void updateProblemType(SiteProblemTypeEnum problemType, DateTime updateTime) {
        upsert(
                F.PROBLEM_TYPE.value(problemType),
                F.LAST_UPDATE.value(updateTime)
        ).execute();
    }

    public Map<SiteProblemTypeEnum, DateTime> getLastUpdateInfos() {
        Map<SiteProblemTypeEnum, DateTime> result = new HashMap<>();
        streamReader(MAPPER, e -> result.put(e.getProblemType(), e.getLastUpdate()));
        return result;
    }

    public DateTime getLastUpdate(SiteProblemTypeEnum problemType) {
        return select(F.LAST_UPDATE).where(F.PROBLEM_TYPE.eq(problemType)).queryOne();
    }

    private static final DataMapper<Record> MAPPER = DataMapper.create(F.PROBLEM_TYPE, F.LAST_UPDATE, Record::new);

    private static class Record {
        final SiteProblemTypeEnum problemType;
        final DateTime lastUpdate;

        public Record(SiteProblemTypeEnum problemType, DateTime lastUpdate) {
            this.problemType = problemType;
            this.lastUpdate = lastUpdate;
        }

        public SiteProblemTypeEnum getProblemType() {
            return problemType;
        }

        public DateTime getLastUpdate() {
            return lastUpdate;
        }
    }

    protected static class F {
        static final Field<SiteProblemTypeEnum> PROBLEM_TYPE = Fields.intEnumField("problem_type", SiteProblemTypeEnum.R);
        static final Field<DateTime> LAST_UPDATE = Fields.jodaDateTimeField("last_update");
    }
}
