package com.codingame.game;

import java.util.List;
import java.util.Random;

import java.util.regex.Pattern;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;

import com.codingame.gameengine.core.AbstractMultiplayerPlayer;
import com.codingame.gameengine.module.entities.Group;
import com.codingame.gameengine.module.entities.Text;
import com.codingame.gameengine.module.entities.Sprite;

public class Player extends AbstractMultiplayerPlayer {
    Model.Player model;
    View.Player view;

    @Override
    public int getExpectedOutputLines() {
        return 1;
    }

    // same-typed positional parameters… a disaster waiting to happen
    void gameInit(int roadLength, int initialStones, long seed, long salt) {
        sendInputLine(String.format("%d %d %d %d %d",
                                    roadLength, initialStones, seed,
                                    model.getMultiplier(), salt));
    }

    void sendGameTurn() {
        type = null;             //
        stoneThrow = null;       // correctness over stability!
        messageString = null;    //

        sendInputLine(String.format("%d %d %d",
                                    model.getTrollDistance(),
                                    model.getStones(),
                                    model.getOppStones()));
        execute();
    }

    static enum Action { Throw, Timeout, Invalid }
    Action type;
    Integer stoneThrow;
    String messageString;

    private void reportMsg(String tag) {
        System.err.println("Message @" + tag + ": " + messageString);
    }

    void receiveGameTurn() {
        messageString = "";
        try { messageString = getOutputs().get(0); }
        catch (TimeoutException e) { type = Action.Timeout; return; }

        Scanner s = new Scanner(messageString);
        try { stoneThrow = s.nextInt(); }
        catch (InputMismatchException e) { type = Action.Invalid; return; }
        catch (NoSuchElementException e) { type = Action.Invalid; return; }

        s.useDelimiter(eol);
        if (s.hasNext(rest)) messageString = s.next(rest).trim();
        else messageString = "";
        type = Action.Throw;
    }

    private static final Pattern rest = Pattern.compile(".*");
    private static final Pattern eol = Pattern.compile("\n");
}
