package eu.eudat.logic.managers;

import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.dao.entities.UserInfoDao;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.data.entities.UserRole;
import eu.eudat.data.query.items.table.userinfo.UserInfoTableRequestItem;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.builders.entity.UserRoleBuilder;
import eu.eudat.logic.builders.model.models.DataTableDataBuilder;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.logic.utilities.builders.XmlBuilder;
import eu.eudat.models.HintedModelFactory;
import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.login.Credentials;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.userinfo.UserListingModel;
import eu.eudat.models.data.userinfo.UserProfile;
import eu.eudat.queryable.QueryableList;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class UserManager {

	private ApiContext apiContext;

	@Autowired
	public UserManager(ApiContext apiContext) {
		this.apiContext = apiContext;
	}

	public eu.eudat.models.data.user.composite.DatasetProfile generateDatasetProfileModel(eu.eudat.data.entities.DatasetProfile profile) {
		Document viewStyleDoc = XmlBuilder.fromXml(profile.getDefinition());
		Element root = (Element) viewStyleDoc.getDocumentElement();
		eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel viewstyle = new eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel().fromXml(root);

		eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = new eu.eudat.models.data.user.composite.DatasetProfile();
		datasetprofile.buildProfile(viewstyle);

		return datasetprofile;
	}

	public DataTableData<UserListingModel> getPaged(UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
		QueryableList<eu.eudat.data.entities.UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().getWithCriteria(userInfoTableRequestItem.getCriteria()).withHint(HintedModelFactory.getHint(UserListingModel.class));
		QueryableList<eu.eudat.data.entities.UserInfo> pagedUsers = PaginationManager.applyPaging(users, userInfoTableRequestItem);

		List<UserListingModel> modelUsers = pagedUsers.select(item -> new UserListingModel().fromDataModel(item));
		return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).totalCount(users.count()).data(modelUsers).build();
	}

	public UserProfile getSingle(UUID userId) throws Exception {
		eu.eudat.data.entities.UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userId);
		UserProfile profile = new UserProfile().fromDataModel(user);
		List<Integer> roles = new LinkedList<>();
		List<DMP> dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable(), userId, roles).take(5).toList();
		profile.setAssociatedDmps(dmps.stream().map(x -> new DataManagementPlan().fromDataModel(x)).collect(Collectors.toList()));
		return profile;
	}

	public void editRoles(UserListingModel user) {
		eu.eudat.data.entities.UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(user.getId());
		userInfo.getUserRoles().stream().forEach(item -> apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().delete(item));
		for (Integer role : user.getAppRoles()) {
			UserRole userRole = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserRoleBuilder.class).role(role).userInfo(userInfo).build();
			apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(userRole);
		}
	}

	public void updateSettings(Map<String, Object> settings, Principal principal) throws IOException {
		eu.eudat.data.entities.UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
		apiContext.getOperationsContext().getDatabaseRepository().detachEntity(userInfo);
		HashMap<String, Object> result =
				new ObjectMapper().readValue(userInfo.getAdditionalinfo(), HashMap.class);
		result.putAll(settings);
		userInfo.setAdditionalinfo(new JSONObject(result).toString());
		apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao()
				.createOrUpdate(userInfo);
	}

	public Principal authenticate(AuthenticationService authenticationServiceImpl, Credentials credentials) throws NullEmailException {
		Principal principal = authenticationServiceImpl.Touch(credentials);
		if (principal == null) throw new UnauthorisedException("Could not Sign In User");
		return principal;
	}

	public DataTableData<UserListingModel> getCollaboratorsPaged(UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception {
		UserInfoDao userInfoDao = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao();
		QueryableList<UserInfo> users = userInfoDao.getWithCriteria(userInfoTableRequestItem.getCriteria());

		List<UserListingModel> colaborators = userInfoDao.getAuthenticated(users, principal.getId())
				.withHint(HintedModelFactory.getHint(UserListingModel.class))
				.select(colaborator -> new UserListingModel().fromDataModel(colaborator));

		DataTableData<UserListingModel> dataTableData = new DataTableData<>();
		dataTableData.setData(colaborators);
		dataTableData.setTotalCount((long) colaborators.size());
		return dataTableData;
	}
}
