
import java.util.logging.Logger;

// 1. Https
import java.net.URL;
import java.io.*;
import javax.net.ssl.HttpsURLConnection;

// 2. json deser
//import org.codehaus.jackson.map.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonAutoDetect;

class IntrospectResponse
{
   private static final Logger LOGGER = Logger.getLogger("IntrospectResponse");

   public boolean active;
   public String  scope;

   public IntrospectResponse(String uPass, String url, String token) throws Exception
   {
      final String POST_PARAM = "token=" + token;
      String resp = doHttps(uPass, url, POST_PARAM);
      decodeIRespJson(resp);
   }

   public boolean isTokenActive() { return active; }

   public String getPathFromStorageReadScope()
   {
      if(scope == null)
      {
         throw new IllegalStateException("Introspect Response has scope = null. Probably token not active.");
      }
      else
      {
         String[] scopes = scope.split(" ");
         for(String scope : scopes)
         {
            if(scope.startsWith("storage.read:"))
            {
               return scope.substring("storage.read:".length());
            }
         }
         throw new IllegalStateException(
               "Introspect Response with 'storage.read' scope expected, but received scope: " + scope);
      }
   }



   private String doHttps(String uPass, String url, String postParams) throws Exception
   {
      LOGGER.info("doHttps : " + url);

      URL myUrl = new URL(url);
      HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();
      conn.setRequestMethod("POST");

      String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(uPass.getBytes());

      conn.setRequestProperty ("Authorization", basicAuth);


      conn.setDoOutput(true);
      OutputStream os = conn.getOutputStream();
      os.write(postParams.getBytes());
      os.flush();
      os.close();

      InputStream is = conn.getInputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);

      String inputLine;
      String jsonKeys = "";
      while ((inputLine = br.readLine()) != null) {
         jsonKeys = jsonKeys + inputLine;
      }

      br.close();

      return jsonKeys;
   }
   /*
      @JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.ANY);
      static class IResp
      {
      boolean active;
      String[] scope;
      }
      */
   private void decodeIRespJson(String json) throws IOException
   {
      ObjectMapper mapper = new ObjectMapper();
      active = mapper.readTree(json).get("active").asBoolean();
      if(active)
      {
         scope = mapper.readTree(json).get("scope").asText();
      }
   }

}
