package ua.be.typeOperations.controllers;

import java.io.File;
import java.io.IOException;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import ua.be.typeOperations.model.csv.CSVOperationManager;
import ua.be.typeOperations.model.csv.operations.OutlierDetectionOperation;

@RestController
@RequestMapping("/api/csv")
public class CSVController {
 
	@PostMapping(path="/outlier", consumes="application/json", produces="text/plain")
	public ResponseEntity<String> outliers(@RequestBody OutlierRequest request) {
		int column = request.getColumn();
		String iri = request.getIri();
		String prefix = iri.substring(1,iri.indexOf('#')+1);
    	String instance = iri.substring(iri.indexOf('#')+1, iri.length()-1);
		String file = request.getFile();
		String result;
		CSVOperationManager.getInstance().setOperation(new OutlierDetectionOperation(column,prefix, instance));
		try {
			result = CSVOperationManager.getInstance().executeCSVOperation(new File("src/main/resources/static/csv/"+file));
		} catch (IOException e) {
			 return ResponseEntity.notFound().build();
		}
    	return ResponseEntity.ok().body(result);
	}

 
    @GetMapping("/outlier/{iri}/{column}/{file}")
    public ResponseEntity<String> findOutliers(@PathVariable(value = "iri") String iri, @PathVariable(value = "column") int column, @PathVariable(value = "file") String file ) {
    	String prefix = iri.substring(1,iri.indexOf('#'));
    	String instance = iri.substring(iri.indexOf('#')+1, iri.length()-1);
    	String result = "";
    	CSVOperationManager.getInstance().setOperation(new OutlierDetectionOperation(column,prefix, instance));
		try {
			result = CSVOperationManager.getInstance().executeCSVOperation(new File("src/main/resources/static/csv/"+file));
		} catch (IOException e) {
			 return ResponseEntity.notFound().build();
		}
    	return ResponseEntity.ok().body(result);
    }
    
    @GetMapping("/outliers/{iri}")
    public ResponseEntity<String> findOutliers(@PathVariable(value = "iri") String iri) {
    	return ResponseEntity.ok().body(iri);
    }
    
    public static void main(String[] args) {
		String iri= "<http://ua.be/drivetrain/description/artifacts/artifacts#drivetrain-sensor-data-v1>";
		String prefix = iri.substring(1,iri.indexOf('#'));
    	String instance = iri.substring(iri.indexOf('#')+1, iri.length()-1);
    	System.out.println(prefix);
    	System.out.println(instance);

	}
 
    
}

