package es.uv.garcosda.services;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import es.uv.garcosda.domain.Document;
import reactor.core.publisher.Flux;

@Service
public class ImportService {
	
	@Autowired
    private NewsService ns;

	private List<Document> generateDocs(List<String> lines) throws JsonMappingException, JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
	    List<Document> docs = new ArrayList<>();
	    for (String e : lines) {
	    	Document x = mapper.readValue(e, Document.class);
	    	x.setId(null);
	    	//System.out.println(x);
	        docs.add(x);
	    }
	    System.out.println("[I] ImportService: readed "+docs.size()+" items");
	    return docs;
	}
	
	private int insert(List<Document> mongoDocs) {
	    try {
	    	Flux<Document> a = ns.createAll(mongoDocs); 
    		a.blockLast();
	        return 1;
	    } 
	    catch (DataIntegrityViolationException e) {
	        return 0;
	    }
	}
		
	public int doImport(Resource resource) throws JsonMappingException, JsonProcessingException {
	    ArrayList<String> jsonlines = new ArrayList<>();
	    try (Scanner s = new Scanner(resource.getFile())) {
	        while (s.hasNext()) {
	        	jsonlines.add(s.nextLine());
	        }
	    }
	    catch(IOException e) {
	    	System.out.println("[ERROR] data file not found");
	    }
	    
	    List<Document> docs = generateDocs(jsonlines);
	    return insert(docs);
	}
	
}
