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.TbVmsSymbLibIfscVMP2Dto;
import com.its.api.its.model.entity.vms.TbVmsSymbIfsc;
import com.its.api.its.model.entity.vms.TbVmsSymbIfscKey;
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.ConcurrentModificationException;

@Slf4j
@Service
public class TbVmsSymbLibVmp2Service extends TbVmsSymbLibService {

    private final TbVmsSymbIfscService ifscService;

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

    public Integer getNewSymbolId() {
        return getNewSymbolId(8000, 8999);
    }

    public TbVmsSymbLibIfscVMP2Dto findAllById(Integer id) {
        TbVmsSymbLib lib = requireOne(id);

        Integer cellId =  1;
        TbVmsSymbIfscKey key = new TbVmsSymbIfscKey(id, cellId);
        TbVmsSymbIfsc ifsc = ifscService.requireOne(key);

        return TbVmsSymbLibIfscVMP2Dto.toDto(lib.toDto(), ifsc.toDto());
    }

    // 데이터 변경 또는 생성-개별(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public TbVmsSymbLibIfscVMP2Dto mergeSymbIfscInfo(TbVmsSymbLibIfscVMP2Dto.TbVmsSymbLibIfscVMP2UpdReq req) {

        // 심볼 정보 저장
        TbVmsSymbLibDto libDto = mergeInfo(req.toLibReq());
        // 셀 정보 저장
        TbVmsSymbIfscDto.TbVmsSymbIfscUpdReq ifscReq = new TbVmsSymbIfscDto.TbVmsSymbIfscUpdReq(
                req.getSymbLibNmbr(), req.getCell().getCellId(), req.getCell().getPosx(), req.getCell().getPosy(), req.getCell().getVmsIfscId()
        );
        TbVmsSymbIfscDto ifscDto = this.ifscService.mergeInfo(ifscReq);

        return TbVmsSymbLibIfscVMP2Dto.toDto(libDto, ifscDto);
    }

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

        return deleteById(id);
    }
}
