package com.algobase.accounts;

import java.lang.StringBuilder;

import java.net.URL;
import java.net.HttpURLConnection;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;


public class GMapTiles {

  public void writeLog(String s) {}
  public void showToast(String s) {}


 String api_key = "";

  String errorText = null;

  String sessionToken = null;
  String imageFormat = "";
  long   expiration = 0;
  int    tileWidth  = 0;
  int    tileHeight = 0;

  public GMapTiles(String key) { api_key = key; }

  public String getSessionToken() { return sessionToken; }
  public String getImageFormat() { return imageFormat; }
  public long getExpiration() { return expiration; }
  public int getTileWidth() { return tileWidth; }
  public int getTileHeight() { return tileHeight; }

  public String getError() { return errorText; }

   String unescapeUnicode(String s)
   { 
     if (s == null) return null;

     String txt = "";

     int p = 0;
     int q = s.indexOf("\\u"); // "\\uxxxx"
     while (q > 0 && s.charAt(q-1) == '\\') q = s.indexOf("\\u",q+1);

     while (q != -1)
     { txt += s.substring(p,q);
       int hex = Integer.parseInt(s.substring(q+2,q+6),16);
       txt += (char)hex;
       p = q+6;
       q = s.indexOf("\\u",p);
       while (q > 0 && s.charAt(q-1) == '\\') q = s.indexOf("\\u",q+1);
      }

     txt += s.substring(p);

     return txt;
   }


  private String jsonValue(String text, String tag, int pos)
  { if (text == null) return null;

    int p = text.indexOf("\"" + tag + "\":",pos);
    if (p == -1) return null;

    p += tag.length() + 3;
    while (text.charAt(p) == ' ') p++;
    if (text.charAt(p) == '"') p++;

    int q = text.indexOf(",",p);
    if (q == -1) q = text.indexOf("}",p);
    if (text.charAt(q-1) == '\n') q--;
    while (text.charAt(q-1) == ' ') q--;
    if (text.charAt(q-1) == '"') q--;

    return text.substring(p,q);
  }


 
  public boolean loadSessionToken(String type, String language, String region)
  { 
    errorText = null;

    String url_str = "https://tile.googleapis.com/v1/createSession";

  //String json = "{'mapType': 'roadmap', 'language': 'en-US', 'region': 'US'}";
  //String json = "{'mapType': 'roadmap', 'language': 'de', 'region': 'DE'}";

    String json = "{'mapType': '"  + type     + "', " + 
                   "'language': '" + language + "', " +
                   "'region': '"   + region   + "', " +
                   "'layerTypes': ['layerRoadmap'] }";

    writeLog("Load SessionToken");
    writeLog(json);
    writeLog("");

    String text = null;

    try {

      URL url = new URL(url_str + "?key=" + api_key);

      HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 
      conn.setRequestMethod("POST");

      conn.setUseCaches(false);
      conn.setDoInput(true);
      conn.setDoOutput(true);

      conn.setRequestProperty("Accept-Charset","UTF-8");
      conn.setRequestProperty("Content-Type", "application/json");

      //conn.connect();

      try(OutputStream os = conn.getOutputStream()) {
        byte[] bytes = json.getBytes("utf-8");
        os.write(bytes,0,bytes.length);
      }

      InputStream is = conn.getInputStream();

      StringBuilder builder = new StringBuilder();

      byte[] buffer = new byte[1024];
       
      int n = 0;
      while ((n = is.read(buffer)) != -1) { 
        builder.append(new String(buffer,0,n));
      }
      is.close();

      text = builder.toString();
      if (text != null) text = unescapeUnicode(text);

      conn.disconnect();

    } catch(Exception e) { text = null; errorText = e.toString(); }


    writeLog("");

    if (errorText != null) 
    { writeLog("Token Error");
      writeLog(errorText);
    }
    else
    { writeLog("Session Token (" + type + ")");
      writeLog(text);
     }

    writeLog("");

    try {
      sessionToken = jsonValue(text,"session",0);
      imageFormat = jsonValue(text,"imageFormat",0);
      expiration = Long.parseLong(jsonValue(text,"expiry",0));
      tileWidth = Integer.parseInt(jsonValue(text,"tileWidth",0));
      tileHeight = Integer.parseInt(jsonValue(text,"tileHeight",0));
    } catch(Exception e) { errorText = e.toString(); }

    return errorText == null;
  }
}
