package eu.dnetlib.organizations.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import eu.dnetlib.common.controller.AbstractDnetController;
import eu.dnetlib.organizations.model.utils.VocabularyTerm;
import eu.dnetlib.organizations.utils.DatabaseUtils;
import eu.dnetlib.organizations.utils.DatabaseUtils.VocabularyTable;
import eu.dnetlib.organizations.utils.RelationType;
import eu.dnetlib.organizations.utils.SimilarityType;

@RestController
public class VocabulariesController extends AbstractDnetController {

	@Autowired
	private DatabaseUtils databaseUtils;

	@GetMapping("/api/vocabularies")
	public Map<String, List<VocabularyTerm>> ListVocabularies(final Authentication authentication) {
		final Map<String, List<VocabularyTerm>> vocs = new HashMap<>();
		vocs.put("orgTypes", databaseUtils.listValuesOfVocabularyTable(VocabularyTable.org_types));
		vocs.put("idTypes", databaseUtils.listValuesOfVocabularyTable(VocabularyTable.id_types));
		vocs.put("languages", databaseUtils.listValuesOfVocabularyTable(VocabularyTable.languages));

		vocs.put("relTypes", Arrays.stream(RelationType.values())
			.map(t -> new VocabularyTerm(t.name(), t.name()))
			.collect(Collectors.toList()));

		vocs.put("similaritiesType", Arrays.stream(SimilarityType.values())
			.map(t -> new VocabularyTerm(t.toString(), t.toString()))
			.collect(Collectors.toList()));

		if (UserInfo.isSimpleUser(authentication) || UserInfo.isNationalAdmin(authentication)) {
			vocs.put("countries", databaseUtils.listCountriesForUser(UserInfo.getEmail(authentication)));
		} else if (UserInfo.isSuperAdmin(authentication)) {
			vocs.put("countries", databaseUtils.listValuesOfVocabularyTable(VocabularyTable.countries));
		} else {
			vocs.put("countries", new ArrayList<VocabularyTerm>());
		}

		return vocs;
	}

	@GetMapping({
		"/api/voc/allCountries", "/registration_api/voc/allCountries"
	})
	public List<VocabularyTerm> allCountries() {
		return databaseUtils.listValuesOfVocabularyTable(VocabularyTable.countries);
	}

}
