package com.agent.management.repository;

import com.agent.management.model.entity.Category;
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 CategoryRepository extends AbstractJsonRepository<Category> {

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

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

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

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

    public List<Category> findByParentIdOrderBySortOrderAsc(Long parentId) {
        List<Category> 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<Category> findAllByOrderBySortOrderAsc() {
        List<Category> list = new ArrayList<>(findAll());
        list.sort(Comparator.comparingInt(c -> c.getSortOrder() == null ? Integer.MAX_VALUE : c.getSortOrder()));
        return list;
    }
}
