package de.thpeetz.kontor.integration.services;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.thpeetz.kontor.media.data.MediaFile;
import de.thpeetz.kontor.media.services.MediaFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AddLinkProcessor implements Processor {

    private final MediaFileService mediaFileService;

    public AddLinkProcessor(MediaFileService mediaFileService) {
        this.mediaFileService = mediaFileService;
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        HashMap<String,String> myMap = objectMapper.readValue(exchange.getIn().getBody().toString(), new TypeReference<HashMap<String,String>>() {});
        String url = myMap.get("url");
        log.info("found url: {}", url);
        MediaFile mediaFile = mediaFileService.findAllMediaFilesByUrl(url);
        if (mediaFile == null) {
            log.info("URL not found, create MediaFile");
            mediaFile = new MediaFile();
            mediaFile.setUrl(url);
            mediaFile.setReview(true);
            mediaFile.setShouldDownload(true);
            MediaFile mediaFileResult = mediaFileService.saveMediaFile(mediaFile);
            log.info("created MediaFile with {}", mediaFileResult.getId());
            exchange.getMessage().getHeaders().put("mediafile_id", mediaFileResult.getId());
        }
        log.info("found MediaFile: {}", mediaFile);
        Map<String, Object> map = exchange.getMessage().getHeaders();
        log.info("Headers: {}", map);
    }
}
