package be.jeffcheasey88.peeratcode.model;

import java.util.Arrays;

public class Completion{
	private int puzzleId;
	private int playerId;
	private int tries;
	private String fileName;
	private byte[] code;
	private int score;
	private String puzzleName;
	
	public Completion(int playerId, int puzzleId, int tries, String fileName, int score) {
		this(playerId, puzzleId, tries, score, fileName, null, null, null, null);
	}
	public Completion(int playerId, int puzzleId, int tries, String fileName, int score, String puzzleName) {
		this(playerId, puzzleId, tries, score, fileName, null, null, null, puzzleName);
	}

	public Completion(int playerId, int puzzleId, String fileName, byte[] file, byte[] response, Puzzle currentPuzzle) {
		this(playerId, puzzleId, 0, 0, fileName, file, response, currentPuzzle, null);
	}
	
	public Completion(int initTries, int initScore) {
		// For group leaderboard
		this(-1, -1, initTries, initScore, null, null, null, null, null);
	}

	public Completion(int playerId, int puzzleId, int tries, int score, String fileName, byte[] file, byte[] response,
			Puzzle currentPuzzle, String initPuzzleName) {
		this.playerId = playerId;
		this.puzzleId = puzzleId;
		this.fileName = fileName;
		if (code != null)
			this.code = Arrays.copyOf(file, file.length);

		// Updated with addTry
		this.tries = tries;
		this.score = score;

		if (currentPuzzle != null)
			addTry(currentPuzzle, response);
		
		puzzleName = initPuzzleName;
	}

	@Override
	public String toString(){
		return "Completion[puzzleId="+puzzleId+", userId="+playerId+",tries="+tries+",score="+score+"]";
	}

	public int getPuzzleId() {
		return puzzleId;
	}

	public int getPlayerId() {
		return playerId;
	}

	public int getTries() {
		return tries;
	}

	public void addTry(Puzzle currentPuzzle, byte[] response) {
		if (score <= 0){
			tries++;
			if (response != null && Arrays.equals(currentPuzzle.getSoluce(), response)) {
				if (tries > 1) { // Loose 5% each try with a minimum of 1 for score
					score = (int) Math.ceil(currentPuzzle.getScoreMax() * (1 - ((tries - 1) / 20.)));
					if (score < 1)
						score = 1;
				} else
					score = currentPuzzle.getScoreMax();
			}
		}
	}
	
	public void updatePlayer(int playerId){
		this.playerId = playerId;
	}

	public String getFileName() {
		return fileName;
	}
	
	public String getPuzzleName() {
		return puzzleName;
	}

	public byte[] getCode() {
		return code;
	}

	public int getScore() {
		return score;
	}
}
