package com.its.op.service.its.vms;

import com.its.op.dao.repository.its.vms.TbVmsFormObjectRepository;
import com.its.op.dao.repository.its.vms.TbVmsSymbLibRepository;
import com.its.op.dto.its.common.UsageCountDto;
import com.its.op.dto.its.vms.TbVmsSymbIfscDto;
import com.its.op.dto.its.vms.TbVmsSymbLibDto;
import com.its.op.dto.its.vms.TbVmsSymbLibIfscSbt1Dto;
import com.its.op.entity.its.vms.TbVmsSymbLib;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;

@Slf4j
@Service
public class TbVmsSymbLibSbt1Service extends TbVmsSymbLibService {

    private final TbVmsSymbIfscService ifscService;

    // 소통정보 배경 이미지
    public TbVmsSymbLibSbt1Service(TbVmsSymbLibRepository repo, TbVmsFormObjectRepository formObjectRepository, TbVmsSymbIfscService ifscService) {
        super("SBT1", 7000, 7999, repo, formObjectRepository);
        this.ifscService = ifscService;
    }
    public TbVmsSymbLibIfscSbt1Dto findAllById(Integer id) {
        TbVmsSymbLib lib = requireOne(id);
        List<TbVmsSymbIfscDto> list = ifscService.findDataById(id);
        return TbVmsSymbLibIfscSbt1Dto.toDto(lib.toDto(), list);
    }

    @Transactional
    public TbVmsSymbLibDto deleteDataById(Integer id) throws ConcurrentModificationException {
        UsageCountDto usageCount = findUsageCountBySymbolId(id);
        if (usageCount.getCount() > 0) {
            throw new ConcurrentModificationException("사용중인 소통정보 배경이미지 입니다. 삭제할 수 없습니다: " + id);
        }
        this.ifscService.deleteDataById(id);

        return deleteById(id);
    }

    @Transactional
    public TbVmsSymbLibIfscSbt1Dto mergeSymbIfscInfo(TbVmsSymbLibIfscSbt1Dto.TbVmsSymbLibIfscVMP1UpdReq req) {

        // 셀 데이터를 전체 삭제
        this.ifscService.deleteDataById(req.getSymbLibNmbr());

        // 심볼 정보 저장
        TbVmsSymbLibDto libDto = mergeInfo(req.toLibReq());
        // 셀 정보 저장
        List<TbVmsSymbIfscDto> cells = new ArrayList<>();
        for (TbVmsSymbIfscDto ifscDto : req.getCells()) {
            TbVmsSymbIfscDto.TbVmsSymbIfscUpdReq ifscReq = new TbVmsSymbIfscDto.TbVmsSymbIfscUpdReq(
                    req.getSymbLibNmbr(), ifscDto.getCellId(), ifscDto.getPosx(), ifscDto.getPosy(), ifscDto.getVmsIfscId()
            );
            cells.add(this.ifscService.mergeInfo(ifscReq));
        }
        return TbVmsSymbLibIfscSbt1Dto.toDto(libDto, cells);
    }
}
