package com.alterdekim.game.service;

import com.alterdekim.game.config.ServerConfig;
import com.alterdekim.game.entity.MediaResource;
import com.alterdekim.game.entity.MediaResourcePath;
import com.alterdekim.game.repository.MRTRepository;
import com.alterdekim.game.repository.MediaResourceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class ResourceService {

    @Autowired
    private MediaResourceRepository mediaResourceRepository;

    @Autowired
    private MRTRepository mrtRepository;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ServerProperties serverProperties;

    public Optional<String> getUrlByMediaResourceId(Long mediaResourceId) {
        Optional<MediaResource> mr = this.mediaResourceRepository.findById(mediaResourceId);
        if( mr.isEmpty() ) return Optional.empty();
        Optional<MediaResourcePath> path = mrtRepository.findById(mr.get().getTId().longValue());
        return path.map(mediaResourcePath -> "http://"+serverConfig.getPublicDomain()+":"+serverProperties.getPort()+"/" + mediaResourcePath.getVal() + mr.get().getUrl());
    }
}
