/*
 * Copyright 2000-2011 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jetbrains.buildServer.tools;

import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jetbrains.buildServer.core.runtime.IProgressMonitor;
import jetbrains.buildServer.core.runtime.IProgressStatus;
import jetbrains.buildServer.core.runtime.RuntimeUtil;
import jetbrains.buildServer.util.FileUtil;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

public class ToolsUtil {

  public static final Logger LOG = Logger.getLogger(ToolsUtil.class);

  public static class LoggerProgressMonitor implements IProgressMonitor {

    private Logger myLogger;
    private boolean isCanceled;

    public LoggerProgressMonitor(Logger logger) {
      myLogger = logger;
    }

    public void beginTask(String taskName) {
      myLogger.info(taskName);
    }

    public void done() {
    }

    public void out(String message) {
      myLogger.info(message);
    }

    public void err(String message) {
      myLogger.error(message);
    }

    public void status(IProgressStatus status) {
      if (status.isOK()) {
        myLogger.debug(status.getMessage(), status.getException());

      } else {
        if (IProgressStatus.INFO == status.getSeverity()) {
          myLogger.info(status.getMessage(), status.getException());

        } else if (IProgressStatus.WARNING == status.getSeverity()) {
          myLogger.warn(status.getMessage(), status.getException());

        } else if (IProgressStatus.ERROR == status.getSeverity()) {
          myLogger.error(status.getMessage(), status.getException());
        }
      }
    }

    public void cancel() {
      isCanceled = true;
    }

    public boolean isCancelled() {
      return isCanceled;
    }

  }

  public static void mainGET(String[] args) throws Exception {
    final HttpClient client = new HttpClient();
    // final HttpClient client = HttpUtil.createHttpClient(5 * 60000 / 1000,
    // new URL("http://javadl.sun.com")/*patchUrl*/, null);
    for (int id = 15000/* 30055 *//* 33000 */; id <= 15100/* 30065 *//* 33150 */; id++) {
      // "http://javadl.sun.com/webapps/download/AutoDL?BundleId=43876"
      final GetMethod get = new GetMethod(String.format("http://javadl.sun.com/webapps/download/AutoDL?BundleId=%d", id));
      try {
        get.setFollowRedirects(false);
        /* final int statusCode = */client.executeMethod(get);
        // System.err.println("Status:" + statusCode);
        // System.err.println("Headers:" +
        // Arrays.toString(get.getResponseHeaders()));
        Header location = get.getResponseHeader("Location");
        if (location != null) {
          System.err.println(String.format("%d=%s", id, location.getValue()));
        }

        // Location
        // System.err.println("Body:   " +
        // get.getResponseBodyAsString());
      } finally {
        get.releaseConnection();
      }
      Thread.sleep(3000);
    }
  }

  public static void mainPARSE(String[] args) throws Exception {
    final List<String> content = FileUtil.readFile(new File("jre-table.txt"));
    for (String line : content) {
      JREParser jre = JREParser.parse(line);
      if (jre != null) {
        System.err.println(jre);
      }
    }
  }

  private static class JREParser {

    private static final Pattern JRE_PATTERN = Pattern.compile("(.*?)=(.*?)jre-(.*?)-(.*?)-(.*?)\\.(.*)\\?(.*)");

    // private static final Pattern SOLARIS_JRE_PATTERN =
    // Pattern.compile("(.*)jre-(.*)-solaris-(.*).sh(.*)");
    // private static final Pattern WINDOWS_JRE_PATTERN =
    // Pattern.compile("(.*)jre-(.*)-windows-(.*).exe(.*)");

    private final String id;
    private final String build;
    private final String version;
    private final String platform;
    private final String arch;
    private final String file;

    static JREParser parse(String line) {
      line = line.trim();
      if (line.length() > 0) {
        Matcher matcher = JRE_PATTERN.matcher(line);
        if (matcher.matches()) {
          String id = matcher.group(1);
          String path = matcher.group(2);
          String[] patSegments = path.split("/");
          String build = patSegments[patSegments.length - 1].split("-")[1];
          String version = matcher.group(3);
          String platform = matcher.group(4);
          String arch = matcher.group(5).split("-")[0];
          String file = line.substring(matcher.end(2), matcher.end(6));
          return new JREParser(id, build, version, platform, arch, file);
        }
      }
      return null;
    }

    private JREParser(String id, String build, String version, String platform, String arch, String file) {
      this.id = id;
      this.build = build;
      this.version = version;
      this.platform = platform;
      this.arch = arch;
      this.file = file;
    }

    @Override
    public String toString() {
      return String.format("id=%s platform=%s arch=%s version=%s build=%s file='%s'", id, platform, arch, version, build, file);
    }
  }

  public static void main(String[] args) throws Exception {
    //    System.err.println(new URI(new LastJDKUrlProvider().toString()));

    final String id = "jdk-6u21-oth-JPR@CDS-CDS_Developer";
    final URL url = new URL("https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=" + id);
    File tmp = File.createTempFile(id, ".tmp");
    RuntimeUtil.URIDownloader.load(url.toURI(), tmp, RuntimeUtil.CONSOLE_MONITOR);
  }

}

// 43870=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-linux-i586-rpm.bin?e=1295445284652&h=6233038564b859c5871ddb00849f131a
// 43871=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-linux-i586.bin?e=1295445287835&h=b88361ceaad6eac12fda0743ac56400f
// 43872=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-linux-ia64-rpm.bin?e=1295445290896&h=02dabc8ccb66045876eecb9fe726efc7
// 43873=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-linux-ia64.bin?e=1295445294096&h=6a0ed2a89c49163347b319c40f31947d
// 43874=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-linux-x64-rpm.bin?e=1295445297277&h=50a5fe1407e58226ef61a60a8a38d64a
// 43875=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-linux-x64.bin?e=1295445300621&h=e928aead541519c22bf9abd9a31890f8
// 43876=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-solaris-i586.sh?e=1295445101719&h=4c8cd9b7c5549a1ae440e1dfa0b2c68a
// 43877=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-solaris-sparc.sh?e=1295445105147&h=a46deb6169a5d813661408e15e471ac9
// 43878=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-solaris-sparcv9.sh?e=1295445108992&h=261ab38219aaee5f0885d7feb00c1b56
// 43879=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-solaris-x64.sh?e=1295445112989&h=2da48227a0b94bcccd6f9dc6bdc3b06f
// 43880=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-windows-i586-s.exe?e=1295445117159&h=3f902e861453006c7b448ba883050b3d
// 43881=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-windows-i586.exe?e=1295445121190&h=a666f498828dc5ec8d168863bff15927
// 43882=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-windows-ia64.exe?e=1295445124982&h=d7bbc8b701a52847577b8a2cbc8a2814
// 43883=http://dl8-cdn-ll.sun.com/s/ESD6/JSCDL/jdk/6u23-b05/jre-6u23-windows-x64.exe?e=1295445128954&h=e635939bc8275816e9bbecc5799bc8ce