package com.macfaq.net.www.protocol.mailto;

import java.net.*;
import java.io.*;
import java.util.*;

public class Handler extends URLStreamHandler {

  protected URLConnection openConnection(URL u) throws IOException {
    return new MailtoURLConnection(u);
  }

  public int getDefaultPort() {
    return 25;
  }
  
  public void parseURL(URL u, String spec, int start, int limit) {
    
    String protocol  = u.getProtocol();
    String host      = "";
    int    port      = u.getPort();
    String file      = ""; // really username
    String userInfo  = null;
    String authority = null;
    String query     = null;
    String ref       = null;
  
    if( start < limit) {
      String address = spec.substring(start, limit);
      int atSign = address.indexOf('@');
      if (atSign >= 0) {
        host = address.substring(atSign+1);
        file = address.substring(0, atSign);
      }
    }
    
    // For Java 1.2 comment out this next line
   this.setURL(u, protocol, host, port, authority, 
                  userInfo, file, query, ref);
    
    // In Java 1.2 and earlier uncomment the following line:
    // this.setURL(u, protocol, host, port, file, ref);
          
  }

  protected String toExternalForm(URL u) {
    return "mailto:" + u.getFile() + "@" + u.getHost();;   
  }
  
  public static void main(String[] args) {
    
    for (int i = 0; i < args.length; i++) {
      try {
        Handler h = new Handler();
        URL u = new URL(null, args[i], h);
        int start = 0;
        int limit = args[i].indexOf('#');
        if (limit == -1) limit = args[i].length();
    //    h.parseURL(u, args[i], start, limit);
        
        System.out.println("The URL is " + u);
        System.out.println("The scheme is " + u.getProtocol());        
        System.out.println("The user info is " + u.getUserInfo());
        
        System.out.println("The host is " + u.getHost());   

        System.out.println("The port is " + u.getPort());
        System.out.println("The path is " + u.getPath());
        System.out.println("The ref is " + u.getRef());
        System.out.println("The query string is " + u.getQuery());
        
      }
      catch (MalformedURLException e) {
        System.err.println(e);   
      }
    }
    
  }

}