package de.jottyfan.camporganizer.module.confirmation.confirmation.impl;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.jooq.exception.DataAccessException;
import org.keycloak.KeycloakSecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import de.jottyfan.camporganizer.module.confirmation.confirmation.IConfirmationService;

/**
 *
 * @author jotty
 *
 */
@Service
public class ConfirmationService implements IConfirmationService {
	@Autowired
	private ConfirmationGateway gateway;

	@Override
	public String getCurrentUser(HttpServletRequest request) {
		KeycloakSecurityContext ksc = (KeycloakSecurityContext) request
				.getAttribute(KeycloakSecurityContext.class.getName());
		if (ksc == null) {
			throw new DataAccessException("no keycloak user in session");
		}
		return ksc.getIdToken().getPreferredUsername();
	}

	@Override
	public List<CampOverviewBean> getCampOverview(HttpServletRequest request) {
		return gateway.getCampOverviewBeans(getCurrentUser(request));
	}

	@Override
	public List<BookingBean> getUntouched(HttpServletRequest request) {
		return gateway.getUntouched(getCurrentUser(request));
	}

	@Override
	public List<BookingBean> getApproved(HttpServletRequest request) {
		return gateway.getApproved(getCurrentUser(request));
	}

	@Override
	public List<BookingBean> getRejected(HttpServletRequest request) {
		return gateway.getRejected(getCurrentUser(request));
	}

	@Override
	public String search(String needle, String linkURL, HttpServletRequest request) {
		StringBuilder buf = new StringBuilder(
				"<table class=\"table table-striped\"><thead><tr><th>Dabei</th><th>Name</th><th>Freizeit</th><th>Rolle</th></tr><tbody>");
		for (BookingBean bean : gateway.getSearchResult(needle, getCurrentUser(request))) {
			String acceptHtml = "";
			if (bean.getAccept() == null) {
				acceptHtml = "<i class=\"fas fa-question framed framed-orange\"></i>";
			} else if (bean.getAccept()) {
				acceptHtml = "<i class=\"fas fa-check framed framed-green\"></i>";
			} else {
				acceptHtml = "<i class=\"fas fa-ban framed framed-red\"></i>";
			}
			buf.append(String.format("<tr><td>%s</td><td><a href=\"%s/%d\">%s</a></td><td>%s</td><td>%s</td></tr>",
					acceptHtml, linkURL, bean.getPkPerson(), bean.getFullname(), bean.getCamp(), bean.getRolename()));
		}
		buf.append("</tbody></table>");
		return buf.toString();
	}
}
