public class KPIGenHelper {
  private static Logger log = LoggerHelper.getLogger();

  public static String replace(String sql, Date date) {
    String regx = "(#.*?#)";
    Pattern pattern = Pattern.compile(regx);
    Matcher matcher = pattern.matcher(sql);

    for (int i = 1; matcher.find(); i++) {
      String placeHolder = matcher.group();
      String inPattern = placeHolder.replaceAll("#", "");
      String val = new SimpleDateFormat(inPattern).format(date);
      // log.info(i + ". " + val);
      sql = sql.replaceAll(placeHolder, val);
    }
    return sql;
  }

  public static void main(String[] args) {
    String sql = "#YYYY# '#YYYY#' ) T WHERE T.PERIOD = '#YYYYMMdd#'";
    sql = KPIGenHelper.replace(sql, new Date());
    log.info(sql);
  }

  public static DataSource getDS(KPIGenProperties p) throws SQLException, IOException {
    if ("DB2".equalsIgnoreCase(p.get("DB"))) {
      DB2SimpleDataSource ds = new DB2SimpleDataSource();
      ds.setDriverType(4);
      ds.setLoginTimeout(5); // sec
      ds.setServerName(p.get("ServerName"));
      ds.setPortNumber(Integer.parseInt(p.get("PortNumber")));
      ds.setDatabaseName(p.get("DatabaseName"));
      ds.setUser(p.get("User"));
      ds.setPassword(p.get("Password"));
      return ds;
    } else {
      OracleDataSource ds = new OracleDataSource();
      ds.setDriverType("thin");
      ds.setServerName(p.get("ServerName"));
      ds.setPortNumber(Integer.parseInt(p.get("PortNumber")));
      ds.setDatabaseName(p.get("DatabaseName"));
      ds.setUser(p.get("User"));
      ds.setPassword(p.get("Password"));
      return ds;
    }
  }
}
public class ProxyProcessHelper {
  static Logger log = LoggerHelper.getLogger();

  private static HttpURLConnection getAFGConnction(String sipUri, String method)
      throws IOException {
    String urlStr = Env.get("afgHostContext");
    urlStr += StringUtils.isNotBlank(Env.get("afgHostContextSuffix")) ? "/" : "?";
    urlStr += sipUri;
    urlStr += Env.get("afgHostContextSuffix");
    URL url = new URL(urlStr);
    log.debug("AFG url=" + url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(method);
    conn.setRequestProperty("X-3GPP-Asserted-Identity", sipUri);
    return conn;
  }

  // Send HTTP GET to AFG using MSISDN from EMM HTTP PUT URI in order to get Ericsson XML
  public static String queryAFG(String sipUri) throws Exception {
    String r;
    // query xml from AFG
    HttpURLConnection conn = getAFGConnction(sipUri, "GET");

    // read response
    conn.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String temp = null;
    StringBuilder sb = new StringBuilder();
    while ((temp = in.readLine()) != null) {
      sb.append(temp).append(" ");
    }
    r = sb.toString();
    IOUtils.closeQuietly(in);

    // r = fakeECTXml();
    log.debug(r);
    return r;
  }

  public static String fakeECTXml() throws IOException, ClassNotFoundException {
    String r;
    // String filename = "ericsson activate CFU.xml";
    String filename = "ericsson deactivate CFU.xml";
    log.debug(filename);
    // log.debug(ClassUtils.getClass(ProxyProcessHelper.class.getName()).getClassLoader().getResource(filename));
    r =
        IOUtils.toString(
            ClassUtils.getClass(ProxyProcessHelper.class.getName())
                .getClassLoader()
                .getResourceAsStream(filename));
    return r;
  }

  public static String updateAFGXml(boolean isActivate, String target, String ectXml) {
    String conditionStr =
        isActivate ? "<cp:conditions/>" : "<cp:conditions><ss:rule-deactivated/></cp:conditions>";
    Document doc = Jsoup.parse(ectXml, "UTF-8");
    Elements ruleAudio = doc.select("cp|rule[id=cfu] ");

    Elements ruleAudioCondition = ruleAudio.select("cp|conditions");
    ruleAudioCondition.remove(); // we cant change it to "<cp:conditions/> directly
    ruleAudio.prepend(conditionStr);

    Elements ruleAudioForwardTarget = ruleAudio.select("ss|forward-to>ss|target");
    ruleAudioForwardTarget.html(target);

    String r = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    r += doc.getElementsByTag("ss:simservs").outerHtml();

    // modify for jsoup problem
    r = r.replaceAll("noreplytimer", "NoReplyTimer");
    // r= r.replaceAll("\n", "");
    r = r.replaceAll(">\\s+(.+)\\s+<", ">$1<");

    return r;
  }

  public static void main(String[] args) throws Exception {
    String ectXml = fakeECTXml();
    String a = updateAFGXml(false, "0897335215", ectXml);
    System.out.println(a);
  }

  public static void updateAFG(String sipUri, String ectXml) throws Exception {
    // put to AFG-Proxy
    HttpURLConnection conn = getAFGConnction(sipUri, "PUT");
    conn.setRequestProperty("Content-Type", "application/simservs+xml");
    conn.setDoOutput(true);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(ectXml);
    IOUtils.closeQuietly(out);

    // read response
    conn.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String temp = null;
    StringBuilder sb = new StringBuilder();
    while ((temp = in.readLine()) != null) {
      sb.append(temp);
    }
    log.debug("AFG Server Answer: " + sb.toString());
    IOUtils.closeQuietly(in);
  }
}