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.TbVmsSymbLibIfscSbt2Dto;
import com.its.op.entity.its.vms.TbVmsSymbIfsc;
import com.its.op.entity.its.vms.TbVmsSymbIfscKey;
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.ConcurrentModificationException;

@Slf4j
@Service
public class TbVmsSymbLibSbt2Service extends TbVmsSymbLibService {

    private final TbVmsSymbIfscService ifscService;

    // 소통정보 이미지
    public TbVmsSymbLibSbt2Service(TbVmsSymbLibRepository repo, TbVmsFormObjectRepository formObjectRepository, TbVmsSymbIfscService ifscService) {
        super("VMP2", 8000, 8999, repo, formObjectRepository);
        this.ifscService = ifscService;
    }

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

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

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

    // 데이터 변경 또는 생성-개별(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public TbVmsSymbLibIfscSbt2Dto mergeSymbIfscInfo(TbVmsSymbLibIfscSbt2Dto.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 TbVmsSymbLibIfscSbt2Dto.toDto(libDto, ifscDto);
    }

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

        return deleteById(id);
    }
}
