package com.izouma.nineth.service;

import com.izouma.nineth.domain.Tag;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.repo.TagRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

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

@Service
@AllArgsConstructor
public class TagService {

    private TagRepo tagRepo;

    public Page<Tag> all(PageQuery pageQuery) {
        return tagRepo.findAll(JpaUtils.toSpecification(pageQuery, Tag.class), JpaUtils.toPageRequest(pageQuery));
    }

    public Object checkAdd(String addMode, String pattern) {
        Map<String, Object> map = new HashMap<>();
        if ("easy".equals(addMode)) {
            map.put("asset", tagRepo.countAssetEasy("%" + pattern + "%"));
            map.put("collection", tagRepo.countCollectionEasy("%" + pattern + "%"));
        } else if ("regex".equals(addMode)) {
            map.put("asset", tagRepo.countAssetRegex(pattern));
            map.put("collection", tagRepo.countCollectionRegex(pattern));
        }
        return map;
    }

    public Tag create(String name, String remark, boolean addForExist, String addMode, String pattern) {
        Tag tag = tagRepo.saveAndFlush(Tag.builder()
                .name(name)
                .remark(remark)
                .build());
        if (addForExist) {
            if ("easy".equals(addMode)) {
                tagRepo.addTagForAssetEasy(tag.getId(), "%" + pattern + "%");
                tagRepo.addTagForCollectionEasy(tag.getId(), "%" + pattern + "%");
            } else if ("regex".equals(addMode)) {
                tagRepo.addTagForAssetRegex(tag.getId(), pattern);
                tagRepo.addTagForCollectionRegex(tag.getId(), pattern);
            }
        }
        return tag;
    }
}
