from java.io import File, FileInputStream;
from java.lang import Boolean;
from java.util import HashMap, Properties, TreeMap;
from org.codehaus.jettison.json import JSONObject, JSONArray;
from WASConfLog import Log;
from utilities import Util;
import sys;
import os;
import Queue;

class MapHelper:
  def __init__(self, map):
    self.map = map;

  def getDescendentsFromTreeMap(self, path):
    return self.map.subMap(path + "/", Boolean.FALSE, path + "0", Boolean.FALSE);

  def findHighestNoneApplicablePath(self, path, appTypes):
    map = self.map;
    #remove training slash because i don't trust people
    while path.endswith("/"):
      path = path[0:-1];

    #ensure it starts with a slash
    if not path.startswith("/"):
      path = "/" + path;

    prev = path;
    found = None;
    while len(path) > 0 and found is None:
      slashindex = path.rfind("/");
      path = path[0:slashindex];
      if len(path) > 0:
        resource = map.get(path);
        if resource is None:
          Log.debug("No resource in map for path %s" % path);
        else:
          if resource.has("roleName"):
            rolename = resource.getString("roleName");
            type = Util.roleNameToType(rolename);
            if appTypes.has_key(type):
              found = prev;
            else:
              prev = path;
    return found;

  def getAncestorsFromTreeMap(self, path):
    map = self.map;
    returnlist = [];
    #remove training slash because i don't trust people
    while path.endswith("/"):
      path = path[0:-1];

    #ensure it starts with a slash
    if not path.startswith("/"):
      path = "/" + path;

    #note we dont want this method to return the passed in resource
    while len(path) > 0:
      slashindex = path.rfind("/");
      path = path[0:slashindex];
      if len(path) > 0:
        resource = map.get(path);
        if resource is None:
          Log.debug("No resource in map for path %s" % path);
        else:
          returnlist.append(resource);

    return returnlist;

  def put(self, path, value):
    return self.map.put(path, value);

  def get(self, path):
    return self.map.get(path);
