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

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;

import org.springframework.stereotype.Service;

import de.jottyfan.camporganizer.module.confirmation.board.model.PersonBean;

/**
 *
 * @author jotty
 *
 */
@Service
public class List2CSVService {
	private static final String QUOTE = "\"";
	private static final String SEP = ";";

	private StringBuilder append(StringBuilder buf, String s) {
		return buf.append(s == null || s.isEmpty() ? SEP : String.format("%s%s%s%s", QUOTE, s, QUOTE, SEP));
	}

	private StringBuilder append(StringBuilder buf, Double d) {
		return buf.append(d == null ? SEP : new Formatter(Locale.GERMAN).format("%.2f%s", d, SEP));
	}

	private StringBuilder append(StringBuilder buf, Boolean b) {
		return buf.append(b == null ? SEP : String.format("%s%s%s%s", QUOTE, b ? "ja" : "nein", QUOTE, SEP));
	}

	private StringBuilder append(StringBuilder buf, LocalDateTime l) {
		return buf.append(l == null ? SEP
				: String.format("%s%s%s%s", QUOTE, l.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm")), QUOTE, SEP));
	}

	private StringBuilder append(StringBuilder buf, LocalDate l) {
		return buf.append(l == null ? SEP
				: String.format("%s%s%s%s", QUOTE, l.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")), QUOTE, SEP));
	}

	public String toCsv(List<PersonBean> list) {
		StringBuilder buf = new StringBuilder();
		String title = String.format(
				"Bezahlt%sVorname%sNachname%sStrasse%sPLZ%sOrt%sTelefon%sEmail%sGeschlecht%sRolle%sGeburtsdatum%sAnmeldestatus%sAnmeldedatum%sFotoeinverständnis%sKommentar\n",
				SEP, SEP, SEP, SEP, SEP, SEP, SEP, SEP, SEP, SEP, SEP, SEP, SEP, SEP);
		buf.append(title);
		for (PersonBean bean : list) {
			append(buf, bean.getPaid());
			append(buf, bean.getForename());
			append(buf, bean.getSurname());
			append(buf, bean.getStreet());
			append(buf, bean.getZip());
			append(buf, bean.getCity());
			append(buf, bean.getPhone());
			append(buf, bean.getEmail());
			append(buf, bean.getSex());
			append(buf, bean.getCamprolle());
			append(buf, bean.getBirthDate());
			append(buf, bean.getProgress());
			append(buf, bean.getCreated());
			append(buf, bean.getConsentCatalogPhoto());
			append(buf, bean.getComment());
			buf.append("\n");
		}
		return buf.toString();
	}

}
