package com.agent.management.repository;

import com.agent.management.model.entity.WfCategory;
import com.agent.management.repository.json.AbstractJsonRepository;
import com.agent.management.repository.json.JsonStore;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

@Component
public class WfCategoryRepository extends AbstractJsonRepository<WfCategory> {

    public WfCategoryRepository(JsonStore store) {
        super(store, new TypeReference<>() {});
    }

    @Override
    protected String getFileName() {
        return "wf-categories.json";
    }

    @Override
    protected Long getId(WfCategory entity) {
        return entity.getId();
    }

    @Override
    protected void setId(WfCategory entity, Long id) {
        entity.setId(id);
    }

    public List<WfCategory> findByParentIdOrderBySortOrderAsc(Long parentId) {
        List<WfCategory> list = new ArrayList<>(findAll(c -> Objects.equals(c.getParentId(), parentId)));
        list.sort(Comparator.comparingInt(c -> c.getSortOrder() == null ? Integer.MAX_VALUE : c.getSortOrder()));
        return list;
    }

    public List<WfCategory> findAllByOrderBySortOrderAsc() {
        List<WfCategory> list = new ArrayList<>(findAll());
        list.sort(Comparator.comparingInt(c -> c.getSortOrder() == null ? Integer.MAX_VALUE : c.getSortOrder()));
        return list;
    }
}
