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

import com.its.op.dao.repository.its.link.TbLinkTrafRepository;
import com.its.op.dao.repository.its.link.TbLinkTrafSimpleRepository;
import com.its.op.dto.its.common.TrafDto;
import com.its.op.dto.its.link.TbLinkTrafDto;
import com.its.op.entity.its.link.TbLinkTraf;
import com.its.op.entity.its.link.TbLinkTrafSimple;
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 TbLinkTrafService {

    private final TbLinkTrafRepository repo;
    private final TbLinkTrafSimpleRepository trafRepo;

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

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

    // 데이터 1건 조회(기존 데이터가 반드시 존재해야 함)
    @Transactional(readOnly = true)
    public TbLinkTrafDto findById(Long id) {
        TbLinkTraf entity = requireOne(id);
        return entity.toDto();
    }

    /**
     * 소통정보조회
     * @return
     */
    public List<TrafDto> findAllTraf() {
        List<TrafDto> result = new ArrayList<>();
        List<TbLinkTrafSimple> data = this.trafRepo.findAll();
        data.forEach(obj -> {
            result.add(obj.toDto());
        });
        return result;
    }

    /**
     * 소통정보조회
     * @return
     */
    public List<TbLinkTrafDto> findAllMissTraf() {
        List<TbLinkTrafDto> result = new ArrayList<>();
        List<TbLinkTraf> data = this.repo.findAllMissTraf();
        data.forEach(obj -> {
            result.add(obj.toDto());
        });

        return result;
    }
}
