package com.ecep.contract.ds.other.repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.data.repository.NoRepositoryBean;

import com.ecep.contract.ds.MyRepository;
import com.ecep.contract.model.BaseEnumEntity;

@NoRepositoryBean
public interface BaseEnumEntityRepository<N extends Enum<?>, T extends BaseEnumEntity<N>, ID>
        extends MyRepository<T, ID> {
    List<T> findAllByLang(String lang);

    default Map<N, T> getCompleteMapByLocal(String lang) {
        HashMap<N, T> map = new HashMap<>();
        for (T t : findAllByLang(lang)) {
            map.put(t.getType(), t);
        }

        ArrayList<T> needSaves = new ArrayList<>();
        for (N type : getEnumConstants()) {
            T v = map.get(type);
            if (v == null) {
                v = newEntity();
                v.setType(type);
                v.setLang(lang);
                v.setValue(type.name());
                needSaves.add(v);
            }
        }
        if (!needSaves.isEmpty()) {
            for (T v : saveAll(needSaves)) {
                map.put(v.getType(), v);
            }
        }
        return map;
    }

    T newEntity();

    N[] getEnumConstants();
}
