/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included  with this distribution in
 * the LICENSE file.
 */

// Contributors:  Mark Womack

package org.apache.log4j.helpers;

import java.io.InputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;

/**
   Return the modification time for a http url, and when asked, return an
   InputStream to the url contents.
   */
public class HTTPWatchdog extends Watchdog {

  /**
     The url to observe for changes.
   */
  protected URL url;
  protected String urlPath;
  private boolean warnedAlready = false;

  public
  HTTPWatchdog() { }
  
  public
  HTTPWatchdog(URL _url) {
    url = _url;
  }
  
  public
  HTTPWatchdog(String _urlPath) {
    urlPath = _urlPath;
  }

  public
  void setUrl(String _urlPath) {
    urlPath = _urlPath;
  }

  public
  void setUrl(URL _url) {
    url = _url;
  }
  
  public
  String getUrl() {
  	if (url != null)
  	  return url.getPath();
  	else
  	  return urlPath;
  }
  
  protected
  long getModificationTime() {
  	
  	long retModTime = 0;
  	
  	// make sure we have a url
  	if (url == null) {
  	  try {
  	  	url = new URL(urlPath);
  	  } catch (MalformedURLException e) {
  	  	LogLog.warn("invalid url, url :["+urlPath+"].");
  	  	this.stopWatching();
  	  	return 0;
  	  }
  	}
  	
  	try {
      HttpURLConnection connection = (HttpURLConnection)url.openConnection();
      
      // request just the headers
  	  connection.setRequestMethod("HEAD");
  	  connection.connect();
  	  
  	  if (connection.getResponseCode() == 200) {
  	    // get the last modified date and return it
  	    retModTime = connection.getLastModified();
 	    warnedAlready = false;
 	  }
 	  else {
	      if (!warnedAlready) {
	        LogLog.warn("error accessing url, response code " + connection.getResponseCode());
	        warnedAlready = true;
	  	  }
 	  }
  	} catch (Exception e) {
      if (!warnedAlready) {
        LogLog.warn("error accessing url: " + e.getMessage());
        warnedAlready = true;
  	  }
  	}
  	
  	return retModTime;
  }

  protected
  InputStream getConfigurationStream() {
  	try {
      HttpURLConnection connection = (HttpURLConnection)url.openConnection();
      
      // request url contents
  	  connection.connect();
  	  
  	  // read past the header
  	  // TODO
  	  
  	  // return an InputStream to the contents
  	  return connection.getInputStream();
  	} catch (Exception e) {
      LogLog.warn("error accessing url: " + e.getMessage());
  	  return null;
  	}
  }
}
