package com.its.op.service.its.link;

import com.its.op.config.ApplicationConfig;
import com.its.op.dao.repository.its.link.TbLinkRepository;
import com.its.op.dto.its.link.TbLinkDto;
import com.its.op.entity.its.link.TbLink;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbLinkService {

    private final ApplicationConfig applicationConfig;
    private final TbLinkRepository repo;

    // 데이터 1건 조회, 없으면 exception
    private TbLink requireOne(Long id) throws NoSuchElementException {
        Optional<TbLink> info = this.repo.findById(id);
        if (info.isPresent()) {
            return info.get();
        }
        else {
            throw new NoSuchElementException("데이터가 존재하지 않습니다: " + id);
        }
//        return repo.findById(id)
//                .orElseThrow(() -> new NoSuchElementException("데이터가 존재하지 않습니다: " + id));
    }

    /**
     * 링크 관리 전체 데이터 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbLinkDto> findAll() {
        List<TbLinkDto> result = new ArrayList<>();
        List<TbLink> data = this.repo.findAll();
        for (TbLink entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

    /**
     * 삭제되지 않은 링크 전체 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbLinkDto> findAllList() {
        List<TbLinkDto> result = new ArrayList<>();
        List<TbLink> data = this.repo.findAllList();
        for (TbLink entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

    // 지역센터 전체 데이터 조회
    @Transactional(readOnly = true)
    public List<TbLinkDto> findLocalAll() {
        List<TbLinkDto> result = new ArrayList<>();
        List<TbLink> data = this.repo.findAll();
        for (TbLink entity : data) {
            if (("LAT001").equals(entity.getAreaCd())) {
                result.add(entity.toDto());
            }
        }
        return result;
    }

    // 지역센터 도로 링크 전체 데이터 조회
    @Transactional(readOnly = true)
    public List<TbLinkDto> findLocalRoadLinkAll() {
        //int regionCode = Integer.parseInt(this.processConfig.getRegionCode());
        List<TbLinkDto> result = new ArrayList<>();
        List<TbLink> data = this.repo.findLocalRoadLinkAll();
        for (TbLink entity : data) {
            //if ((entity.getLinkId() / 10000000) == regionCode) {
                result.add(entity.toDto());
            //}
        }
        return result;
    }

    // 데이터 1건 조회(기존 데이터가 반드시 존재해야 함)
    @Transactional(readOnly = true)
    public TbLinkDto findById(Long id) throws NoSuchElementException{
        try {
            TbLink entity = requireOne(id);
            return entity.toDto();
        }
        catch(NoSuchElementException e) {
            throw e;
        }
    }

    /**
     * 지도검색
     * @param filter
     * @return
     */
    public List<TbLinkDto> findByFilter(String filter) {
        List<TbLinkDto> result = new ArrayList<>();
        List<TbLink> data = this.repo.findAll();
        data.forEach(obj -> {
            if (("Y").equals(obj.getDelYn())) {
                return;
            }
            if (filter == null || filter.isEmpty()) {
                result.add(obj.toDto());
            } else {
                if ((obj.getRoadName() != null && obj.getRoadName().contains(filter)) || String.valueOf(obj.getLinkId()).contains(filter)) {
                    result.add(obj.toDto());
                }
            }
        });
        return result;
    }

    // 도로명 변경
    @Transactional
    public TbLinkDto updateNameById(Long id, TbLinkDto.TbLinkNameUpdReq req) throws NoSuchElementException {
        try {
            TbLink entity = requireOne(id);
            entity.updateName(req);
            this.repo.save(entity);
            return entity.toDto();
        }
        catch(NoSuchElementException e) {
            throw e;
        }
    }

    @Transactional
    public TbLinkDto updateSectGradById(Long id, TbLinkDto.TbLinkSectGradUpdReq req) throws NoSuchElementException {
        try {
            TbLink entity = requireOne(id);
            entity.updateSectGrad(req);
            this.repo.save(entity);
            return entity.toDto();
        }
        catch(NoSuchElementException e) {
            throw e;
        }
    }
}
