package servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import clases.Carta;
import clases.Poker;

/**
 * Servlet implementation class ManoDoc
 */
@WebServlet("/mano_doc")
public class ManoDoc extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManoDoc() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = "https://deckofcardsapi.com/api/deck/new/draw/?count=5";
		
		String json = obtenerJson(url);
		
		Carta[] mano = obtenerCartas(json);
		
		Poker p = new Poker();
		String nombreJugada = p.nombreJugada(mano);
		
		
		for(int i=0; i<mano.length; i++) {
			System.out.println(mano[i].valor + mano[i].palo);
		}
		
		System.out.println(nombreJugada);
		System.out.println("************************");
		
		ArrayList<String> manoString = new ArrayList<String>();
		
		for(int i=0; i<mano.length;i++) {
			if(mano[i].valor.equals("A")) {
				mano[i].valor = "R";
			}
			else if(mano[i].valor.equals("T")){
				mano[i].valor = "B";
			}
			manoString.add(mano[i].valor+mano[i].palo);
		}
		
		Collections.sort(manoString);
		
		for(int i=0; i<mano.length; i++) {
			if(manoString.get(i).charAt(0)=='R') {				
				mano[i] = new Carta("A"+manoString.get(i).charAt(1));
			}
			else if(manoString.get(i).charAt(0)=='B'){
				mano[i] = new Carta("T"+manoString.get(i).charAt(1));
			}
			else {
				mano[i] = new Carta(manoString.get(i));
			}
		}
		
		request.setAttribute("mano", mano);
		request.setAttribute("nombreJugada", nombreJugada);
		
		
		
		RequestDispatcher rd = getServletContext().getRequestDispatcher("/WEB-INF/jsp/mano_doc.jsp");
		rd.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
	
	public static String obtenerJson(String myURL) {
		System.setProperty("http.agent", "Chrome");
		System.out.println("Requested URL:" + myURL);
		StringBuilder sb = new StringBuilder();
		URLConnection urlConn = null;
		InputStreamReader in = null;
		try {
			URL url = new URL(myURL);
			urlConn = url.openConnection();
			if (urlConn != null)
				urlConn.setReadTimeout(60 * 1000);
			if (urlConn != null && urlConn.getInputStream() != null) {
				in = new InputStreamReader(urlConn.getInputStream(),
						Charset.defaultCharset());
				BufferedReader bufferedReader = new BufferedReader(in);
				if (bufferedReader != null) {
					int cp;
					while ((cp = bufferedReader.read()) != -1) {
						sb.append((char) cp);
					}
					bufferedReader.close();
				}
			}
		in.close();
		} catch (Exception e) {
			throw new RuntimeException("Exception while calling URL:"+ myURL, e);
		}
 
		return sb.toString();
	}
	
	public Carta[] obtenerCartas(String json) {
		
		
		JSONObject obj = new JSONObject(json);
		
		JSONArray cartas = obj.getJSONArray("cards");
		
		Carta[] mano= new Carta[5];
		
		for(int i=0; i<mano.length;i++) {
			String valor = cartas.getJSONObject(i).getString("code").substring(0, 1);
			String palo = cartas.getJSONObject(i).getString("code").substring(1, 2);
			
			if(valor.equals("0")) {
				valor = "T";
			}
			
			String carta = valor+palo;
			
			mano[i] = new Carta(carta);
		}
		
		return mano;
	}

}
