package com.its.api.its.service.vms;

import com.its.api.its.repository.vms.TbVmsFormObjectRepository;
import com.its.api.its.model.dto.vms.TbVmsSymbIfscDto;
import com.its.api.its.model.dto.vms.TbVmsSymbLibDto;
import com.its.api.its.model.dto.vms.TbVmsSymbLibIfscVMP1Dto;
import com.its.api.its.model.entity.vms.TbVmsSymbLib;
import com.its.api.its.repository.vms.TbVmsSymbLibRepository;
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 TbVmsSymbLibVmp1Service extends TbVmsSymbLibService {

    private final TbVmsSymbIfscService ifscService;

    public TbVmsSymbLibVmp1Service(TbVmsSymbLibRepository repo, TbVmsFormObjectRepository formObjectRepository, TbVmsSymbIfscService ifscService) {
        super("VMP1", repo, formObjectRepository);
        this.ifscService = ifscService;
    }

    public Integer getNewSymbolId() {
        return getNewSymbolId(7000, 7999);
    }

    public TbVmsSymbLibIfscVMP1Dto findAllById(Integer id) {
        TbVmsSymbLib lib = requireOne(id);
        List<TbVmsSymbIfscDto> list = ifscService.findDataById(id);
        return TbVmsSymbLibIfscVMP1Dto.toDto(lib.toDto(), list);
    }

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

        return deleteById(id);
    }

    @Transactional
    public TbVmsSymbLibIfscVMP1Dto mergeSymbIfscInfo(TbVmsSymbLibIfscVMP1Dto.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 TbVmsSymbLibIfscVMP1Dto.toDto(libDto, cells);
    }
}
