package com.dbnt.kcgfilemanager.service;

import com.dbnt.kcgfilemanager.model.CategoryRole;
import com.dbnt.kcgfilemanager.repository.CategoryRoleRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CategoryRoleService {
  private final CategoryRoleRepository categoryRoleRepository;

  @Transactional
  public void insertCategoryRole(Integer userSeq, List<LinkedHashMap> mapList) {
    categoryRoleRepository.deleteByUserSeq(userSeq);
    List<CategoryRole> categoryRoleList = new ArrayList<>();
    for(LinkedHashMap map: mapList){
      CategoryRole categoryRole = new CategoryRole();
      categoryRole.setUserSeq((int)map.get("userSeq"));
      categoryRole.setCategorySeq((int)map.get("categorySeq"));
      categoryRole.setCategoryRole((String)map.get("categoryRole"));
      categoryRoleList.add(categoryRole);
    }
    categoryRoleRepository.saveAll(categoryRoleList);
  }

  @Transactional
  public void modifyCategoryRole(Integer userSeq, List<Integer> categorySeqList) {
    categoryRoleRepository.deleteByUserSeq(userSeq);
    List<CategoryRole> categoryRoleList = new ArrayList<>();
    for(Integer categorySeq: categorySeqList){
      CategoryRole categoryRole = new CategoryRole();
      categoryRole.setUserSeq(userSeq);
      categoryRole.setCategorySeq(categorySeq);
      categoryRole.setCategoryRole("T");
      categoryRoleList.add(categoryRole);
    }
    categoryRoleRepository.saveAll(categoryRoleList);
  }

  public List<Integer> selectCategorySeqListToUser(CategoryRole categoryRole) {
    List<CategoryRole> categoryRoleList = categoryRoleRepository.findByUserSeq(categoryRole.getUserSeq());
    List<Integer> roleList = new ArrayList<>();
    for(CategoryRole userRole: categoryRoleList){
      roleList.add(userRole.getCategorySeq());
    }
    return roleList;
  }

}
