package eu.eudat.controllers;

import eu.eudat.data.entities.Registry;
import eu.eudat.logic.managers.RegistryManager;
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.registries.RegistryModel;
import eu.eudat.models.data.security.Principal;
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 Registries extends BaseController {

    private RegistryManager registryManager;

    @Autowired
    public Registries(ApiContext apiContext, RegistryManager registryManager) {
        super(apiContext);
        this.registryManager = registryManager;
    }

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

    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = {"/registries"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<RegistryModel>> create(@RequestBody RegistryModel registryModel, Principal principal) throws Exception {
        Registry registry = this.registryManager.create(registryModel, principal);
        RegistryModel registryModel1 = new RegistryModel().fromDataModel(registry);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<RegistryModel>().payload(registryModel1).status(ApiMessageCode.SUCCESS_MESSAGE));
    }
}

