package com.its.op.entity.its.road;

import com.its.op.global.CodeManager;
import com.its.op.dto.its.road.TbRoadRltnIfscDto;
import com.its.op.entity.its.ifsc.TbIfsc;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;

import javax.persistence.*;
import java.io.Serializable;

/**
 * 도로 정보제공구간 관계 Entity Class
 */
@Getter
@NoArgsConstructor//(access = AccessLevel.PROTECTED)
@Builder
@AllArgsConstructor
@ApiModel("도로 정보제공구간 관계")
@Entity
@Table(name = "TB_ROAD_RLTN_IFSC")
@IdClass(TbRoadRltnIfscKey.class)
public class TbRoadRltnIfsc implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty("도로 ID")  // N NUMBER(10)
    @Id
    @Column(name = "ROAD_ID", nullable = false, columnDefinition = "NUMBER", length = 10)
    private Long roadId;

    @ApiModelProperty("정보제공구간 ID")  // N NUMBER(10)
    @Id
    @Column(name = "IFSC_ID", nullable = false, columnDefinition = "NUMBER", length = 10)
    private Long ifscId;

    @ApiModelProperty("순서")  // Y NUMBER(3)
    @Column(name = "ORD", columnDefinition = "NUMBER", length = 3)
    private Integer ord;

    @OneToOne//(fetch = FetchType.EAGER)
    @JoinColumn(insertable=false, updatable=false, name="IFSC_ID", referencedColumnName = "IFSC_ID")
    TbIfsc ifsc;

    public TbRoadRltnIfscDto toDto() {
        TbRoadRltnIfscDto dto;
        if (this.ifsc == null) {
            dto = TbRoadRltnIfscDto.builder()
                    .roadId(this.roadId)
                    .ifscId(this.ifscId)
                    .ord(this.ord)
                    .build();
        }
        else {
            dto = TbRoadRltnIfscDto.builder()
                    .roadId(this.roadId)
                    .ifscId(this.ifscId)
                    .ord(this.ord)
                    .sectLngt(this.ifsc.getSectLngt())
                    .ifscNm(this.ifsc.getIfscNm())
                    .drctCd(this.ifsc.getDrctCd())
                    .fNodeId(this.ifsc.getFNodeId())
                    .tNodeId(this.ifsc.getTNodeId())
                    .sectGradCd(this.ifsc.getSectGradCd())
                    .drctDesc(this.ifsc.getDrctCd())
                    .fromNodeInfo(this.ifsc.getFromNode() != null ? this.ifsc.getFromNode().getNodeName() : "")
                    .toNodeInfo(this.ifsc.getToNode() != null ? this.ifsc.getToNode().getNodeName() : "")
                    .build();

            dto.setDrctDesc(CodeManager.getCodeDesc(CodeManager.DRCT_CD, dto.getDrctCd()));
            dto.setSectGradDesc(CodeManager.getCodeDesc(CodeManager.SECT_GRAD_CD, dto.getSectGradCd()));
        }
        return dto;
    }

    public TbRoadRltnIfsc(Long roadId, Long ifscId) {
        this.roadId = roadId;
        this.ifscId = ifscId;
    }

    public void updateInfo(TbRoadRltnIfscDto.TbRoadIfscRltnUpdReq req) {
        this.ord = req.getOrd();
    }

}
