package w3c.rtsp.common;

import java.io.*;
import java.util.*;
import java.net.*;
import java.awt.*;


public class RtspURL {

  protected String Host=null;
  protected String File=null;
  protected int port=-1;

  public RtspURL(){
  }

  public RtspURL(String rtspurl) throws MalformedURLException{
    int i=0;
    String host_file=null,file=null;
    String line=null,host=null,port_nb=null;
    if(rtspurl.startsWith("rtsp://"))
      host_file=rtspurl.substring(7);
    else 
      throw new MalformedURLException(rtspurl);
    //    System.out.println("\nhost_file:"+host_file);
    try{

      //the port number is specified.

      if(host_file.indexOf(":") != -1){
	int port_len=-1,host_len=-1;
	host_len=host_file.indexOf(":");
	host=host_file.substring(0,host_len);
	port_len=host_file.indexOf("/");
	port_nb=host_file.substring(host_len+1,port_len);
	file=host_file.substring(port_len+1);
      }

      //the port number isn't specified.

      else{
	int host_len=-1;
	host_len=host_file.indexOf("/");
	host=host_file.substring(0,host_len);
	if((host_file.indexOf(host_len,host_file.indexOf('/')))!=-1)
	  file = new String(host_file.substring(host_len+1,host_file.indexOf('/')));
	else
	  file=host_file.substring(host_len+1);
	port_nb="554";
      }
      //      System.out.println("\nFILE :"+file);
    }catch(StringIndexOutOfBoundsException E){
      E.printStackTrace();
      throw new MalformedURLException(rtspurl);
    }
    //  System.out.println("\n port url: "+port_nb.toString());
    this.port=Integer.parseInt(port_nb.toString());
    this.Host=host;
    this.File=file;
    // System.out.println("\nport: "+port+" host: "+host+" file: "+File);
}


  public void setHost(String host){
    this.Host=host;
  }

  public void setFile(String File){
    this.File=File;
  }

  public void setPort(int port){
    this.port=port;
  }

  public String getHost(){
    return this.Host;
  }

  public String getFile(){
    return this.File;
  }

  public int getPort(){
    return this.port;
  }

  //emit the string.

  public void emit(PrintWriter output){
      if((this.Host!=null)&&(this.port!=554))
	output.print("rtsp://"+this.Host+":"+this.port+"/"+this.File);
      else
	output.print("rtsp://"+this.Host+"/"+this.File);
  }
  
  //convert the URL to a string.

  public String toString(){
    return "rtsp://"+this.Host+":"+this.port+"/"+this.File;
  }

  public String getExtensionFile(){
    String result=null;
    if(this.File.indexOf('/',this.File.indexOf('.'))!=-1){
      result = new String(File.substring((this.File.indexOf('.')+1),this.File.indexOf('/',this.File.indexOf('.'))));
      return result;
    }
    else{
      result = new String(File.substring(this.File.indexOf('.')+1));
      return result;
    }
  }
}
