package com.agent.management.repository;

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

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

    @Override
    protected String getFileName() {
        return "tags.json";
    }

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

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

    public List<Tag> findByGroupIdOrderBySortOrderAsc(Long groupId) {
        List<Tag> list = new ArrayList<>(findAll(t -> Objects.equals(t.getGroupId(), groupId)));
        list.sort(Comparator.comparingInt(t -> t.getSortOrder() == null ? Integer.MAX_VALUE : t.getSortOrder()));
        return list;
    }

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

    public void deleteAllByGroupId(Long groupId) {
        deleteAll(t -> Objects.equals(t.getGroupId(), groupId));
    }
}
