package com.mygdx.game.controllers;

import com.badlogic.gdx.Net;
import com.badlogic.gdx.utils.JsonValue;
import com.mygdx.game.Battleship;
import com.mygdx.game.Constants;
import com.mygdx.game.models.*;

import java.util.Timer;
import java.util.TimerTask;

import json.JsonHelper;
import network.NetworkHelper;

/**
 * Created by esso on 16.03.15.
 */
public class PlayerNetworkController {
    private Player player, opponent;
    private boolean playersTurn;
    private Battleship battleshipGame;

    public PlayerNetworkController(Battleship battleshipGame){
        opponent = null;
        player = null;
        playersTurn = false;
    }

    public Player getPlayer() {
        return player;
    }

    public void setPlayer(Player player){
        this.player = player;
    }

    public boolean isPlayersTurn() {
        return playersTurn;
    }

    public void setPlayersTurn(boolean b){playersTurn = b; }

    /**
     * waitForTurn
     * @description Checks regularly if it's this players turn or not
     */
    public void waitForTurn() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                NetworkHelper.sendGetRequest("/turn/" + getPlayer().getUsername(), new Net.HttpResponseListener() {
                    @Override
                    public void handleHttpResponse(Net.HttpResponse httpResponse) {
                        JsonValue jsonResponse = JsonHelper.parseJson(httpResponse.getResultAsString());
                        if (jsonResponse.get("username").equals(getPlayer().getUsername())){
                            setPlayersTurn(true);

                            cancel();
                        } else{
                            setPlayersTurn(false);
                        }
                    }

                    @Override
                    public void failed(Throwable t) {

                    }

                    @Override
                    public void cancelled() {

                    }
                });
            }
        }, Constants.REGULAR_REQUEST_TIME);
    }

    // @todo: we need a method that is called when the opponent fires (fireAtLocation is only called when this player fires??)
    // battleshipGame.getGameScreen().incomingFire(jsonData.x, jsonData.y, true, true);


    /**
     * fireAtLocation
     * @param x
     * @param y
     * @description Takes coordinates and calls to the server that he has fired on that location
     */
    public void fireAtLocation(int x, int y){
        class JsonData {
            private int x, y;
            private String username;
            public void setX(int x) { this.x = x; }
            public void setY(int y) {this.y = y;}
            public void setUsername(String username) {this.username = username;}
        }

        final JsonData jsonData = new JsonData();
        jsonData.setX(x);
        jsonData.setY(y);
        jsonData.setUsername(getPlayer().getUsername());

        NetworkHelper.sendPostRequest("/fire", JsonHelper.buildJson(jsonData), new Net.HttpResponseListener() {
            @Override
            public void handleHttpResponse(Net.HttpResponse httpResponse) {
                // Res: {shipWasHit: BOOLEAN, message: "No game was found" OR "Ongoing game" OR "You lost" OR "You won"}

                JsonValue jsonResponse = JsonHelper.parseJson(httpResponse.getResultAsString());
                if (jsonResponse.get("shipWasHit").asBoolean() == true) {
                    battleshipGame.getGameScreen().incomingFire(jsonData.x, jsonData.y, false, true);
                } else if (jsonResponse.get("shipWasHit").asBoolean() == false){
                    battleshipGame.getGameScreen().incomingFire(jsonData.x, jsonData.y, false, false);
                } else if (jsonResponse.get("message").equals("No game was found")){
                    // @todo DO SOMETHING
                } else if (jsonResponse.get("message").equals("Ongoing game")){
                    // @todo DO SOMETHING
                } else if (jsonResponse.get("message").equals("You lost")) {
                    battleshipGame.setGameOver(false);
                } else if (jsonResponse.get("message").equals("You won")) {
                    battleshipGame.setGameOver(true);
                }

            }

            @Override
            public void failed(Throwable t) {

            }

            @Override
            public void cancelled() {

            }
        });
    }

    public Player getOpponent() {
        return opponent;
    }

    public void setOpponent(Player opponent) {
        if (this.opponent  == null){
            this.opponent = opponent;
        }
    }
}

@@ -200,16 +200,64 @@
 els.*;%0A%0A
+import java.util.Arrays;%0Aimport java.util.List;%0A
 import j
@@ -1658,24 +1658,737 @@
 ername()))%7B%0A
+                            // Handle the response when the opponent fires at your board%0A                            String str = jsonResponse.get(%22lastMove%22).asString();%0A                            List%3CString%3E coordinates = Arrays.asList(str.split(%22,%22));%0A                            int x = Integer.valueOf(coordinates.get(0));%0A                            int y = Integer.valueOf(coordinates.get(1));%0A                            boolean hit = player.getBoard().getCell(x,y).isContainsShip();%0A                            if (x == -1 %7C%7C y == -1) %7B%0A                                hit = false;%0A                            %7D%0A                            battleshipGame.getGameScreen().incomingFire(x, y, true, hit);%0A
             
@@ -2425,17 +2425,16 @@
 (true);%0A
-%0A
         
@@ -2884,231 +2884,15 @@
 E);%0A
+
     %7D%0A%0A
-    // @todo: we need a method that is called when the opponent fires (fireAtLocation is only called when this player fires??)%0A    // battleshipGame.getGameScreen().incomingFire(jsonData.x, jsonData.y, true, true);%0A%0A
 %0A   

Handle incoming fire