package no.valg.valgnatt.backend.mandatberegning.domene;

import java.math.BigDecimal;

public class PartiKvotient implements Comparable<PartiKvotient> {

	private final BigDecimal delingstall;
	private final Kvotient kvotient;
	private final String partikode;
	// Denne settes bare for å gjøre en perfekt sortering, dersom kvotientene er like - ref valglovens krav
	private Integer stemmetall;

	public PartiKvotient(String partikode, Kvotient kvotient, BigDecimal delingstall) {
		this.partikode = partikode;
		this.kvotient = kvotient;
		this.delingstall = delingstall;
	}

	public BigDecimal getDelingstall() {
		return delingstall;
	}

	public int compareTo(PartiKvotient partiKvotient) {
		Kvotient diff = getKvotient().subtract(partiKvotient.getKvotient());
		return diff.getKvotient().compareTo(BigDecimal.ZERO) > 0 ? -1 :
				(diff.getKvotient().compareTo(BigDecimal.ZERO) < 0 ? 1 :
						sammenlignHvisKvotienterErLike(partiKvotient));
	}

	public Kvotient getKvotient() {
		return kvotient;
	}

	private int sammenlignHvisKvotienterErLike(PartiKvotient partiKvotient) {
		if (this.getStemmetall() != null && partiKvotient.getStemmetall() != null) {
			return partiKvotient.getStemmetall() - this.getStemmetall();
		}
		return 0;
	}

	public Integer getStemmetall() {
		return this.stemmetall;
	}

	public void setStemmetall(int stemmetall) {
		this.stemmetall = stemmetall;
	}

	public String toString() {
		return String.format("%.5f (%s)", getKvotient().getKvotient(), getPartikode());
	}

	public String getPartikode() {
		return partikode;
	}

}
