package eu.eudat.controllers;

import eu.eudat.data.query.items.table.userinfo.UserInfoTableRequestItem;
import eu.eudat.exceptions.security.ExpiredTokenException;
import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.doi.DOIRequest;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.userinfo.UserCredential;
import eu.eudat.models.data.userinfo.UserListingModel;
import eu.eudat.models.data.userinfo.UserProfile;
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 javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static eu.eudat.types.Authorities.ADMIN;


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

    private UserManager userManager;
    @Autowired
    public Users(ApiContext apiContext, UserManager userManager) {
        super(apiContext);
        this.userManager = userManager;
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/getPaged"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
        DataTableData<UserListingModel> dataTable = userManager.getPaged(userInfoTableRequestItem);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
    }

    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = {"/updateRoles"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<UserListingModel>> updateRoles(@Valid @RequestBody UserListingModel userListingModel, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
        userManager.editRoles(userListingModel);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserListingModel>().status(ApiMessageCode.NO_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/{id}"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<UserProfile>> get(@PathVariable String id, Principal principal) throws Exception {
        UUID userId = id.equals("me") ? principal.getId() : UUID.fromString(id);
        UserProfile user = userManager.getSingle(userId);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().payload(user).status(ApiMessageCode.NO_MESSAGE));
    }
    
    @RequestMapping(method = RequestMethod.GET, value = {"/{id}/emails"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<List<UserCredential>>> getEmails(@PathVariable String id, Principal principal) throws Exception {
        UUID userId = id.equals("me") ? principal.getId() : UUID.fromString(id);
        List<UserCredential> user = userManager.getCredentials(userId);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<UserCredential>>().payload(user).status(ApiMessageCode.NO_MESSAGE));
    }

    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = {"/settings"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<UserProfile>> saveSettings(@RequestBody Map<String, Object> settings, Principal principal) throws IOException {
        userManager.updateSettings(settings, principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().status(ApiMessageCode.NO_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/getCollaboratorsPaged"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception {
        DataTableData<UserListingModel> dataTable = userManager.getCollaboratorsPaged(userInfoTableRequestItem, principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/hasDOIToken"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<Boolean>> hasDOIToken(Principal principal) throws NullEmailException {
        try {
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Boolean>().payload(this.userManager.isDOITokenValid(principal)).status(ApiMessageCode.NO_MESSAGE));
        } catch (NonValidTokenException | ExpiredTokenException | IOException e) {
            return ResponseEntity.status(460).body(new ResponseItem<Boolean>().payload(false).status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage()));
        }
    }

    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = {"/registerDOIToken"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<UserProfile>> registerDOIToken(@RequestBody DOIRequest doiRequest, Principal principal) throws NullEmailException, IOException {
        userManager.registerDOIToken(doiRequest, principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().status(ApiMessageCode.NO_MESSAGE));
    }

    @Transactional
    @RequestMapping(method = RequestMethod.DELETE, value = {"/deleteDOIToken"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<UserProfile>> deleteDOIToken(Principal principal) throws NullEmailException, IOException {
        userManager.deleteDOIToken(principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().status(ApiMessageCode.NO_MESSAGE));
    }
    
    @RequestMapping(method = RequestMethod.GET, value = {"/getCsv"})
    public @ResponseBody
    ResponseEntity exportCsv(@ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
        return userManager.exportToCsv(principal);
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/find"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<UserProfile>> find(@Valid @RequestBody String email) throws Exception {
        UserProfile userProfile = userManager.getFromEmail(email);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().payload(userProfile).status(ApiMessageCode.NO_MESSAGE));
    }

}

	
	
	
	
	
	
	
	


