package eu.eudat.controllers;

import eu.eudat.data.entities.Service;
import eu.eudat.logic.managers.ServiceManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.services.ServiceModel;
import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@CrossOrigin
@RequestMapping(value = {"/api"})
public class Services extends BaseController {

	private ServiceManager serviceManager;

	@Autowired
	public Services(ApiContext apiContext, ServiceManager serviceManager) {
		super(apiContext);
		this.serviceManager = serviceManager;
	}

	@RequestMapping(method = RequestMethod.GET, value = {"/external/services"}, produces = "application/json")
	public @ResponseBody
	ResponseEntity<ResponseItem<List<ServiceModel>>> listExternalServices(
			@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal
	) throws HugeResultSet, NoURLFound {
		List<ServiceModel> serviceModels = this.serviceManager.getServices(query, type, principal);
		return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<ServiceModel>>().payload(serviceModels).status(ApiMessageCode.NO_MESSAGE));
	}

	@Transactional
	@RequestMapping(method = RequestMethod.POST, value = {"/services"}, consumes = "application/json", produces = "application/json")
	public @ResponseBody
	ResponseEntity<ResponseItem<ServiceModel>> create(@RequestBody ServiceModel serviceModel, Principal principal) throws Exception {
		Service service = serviceManager.create(serviceModel, principal);
		ServiceModel serviceModel1 = new ServiceModel().fromDataModel(service);
		return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ServiceModel>().payload(serviceModel1).status(ApiMessageCode.SUCCESS_MESSAGE));
	}
}

