package edu.csusb.danby.util;

import javax.swing.*;
import java.io.*;
import java.util.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.MalformedURLException;


/**
* class NetFile represents a text file retreived from a specified URL. 
*/
public class NetFile extends Object
{ 
   
    private int numberOfLines;
    private String[] lines;
        //Added by M. Scot McKaskle
        private String urlString;
   
   public NetFile() {
   }

   public NetFile(String URLstring)
   {
     urlString = URLstring;
     openFile(urlString);
   }

   public void openFile(String URLstring){
     InputStream dataIn; 
     Vector strings = new Vector();
     String temp;
    InfoDialog warning;
    
     numberOfLines = 0;
     try{
       try{
         URL url = new URL(URLstring);
         URLConnection connection = url.openConnection();
         BufferedReader ins = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         while((temp = ins.readLine()) != null) {
           strings.addElement(temp);
         }
       } catch (MalformedURLException u)
         { System.out.println ("Unable to open URL");
            warning = new InfoDialog("Warning", "Unable to open URL");
            warning.show();}
     } catch (IOException io)
       { System.out.println ("Can't access the file");
            warning = new InfoDialog("Warning", "Can't access the file");
            warning.show(); }
     lines = new String[strings.size()];
     strings.copyInto(lines);
     numberOfLines = strings.size();
   }


/*
*public accessor methods
*/

   public String[] toArray(){
           return lines;
   }
    
   public int getNumberOfLines(){
           return numberOfLines;
   }

   public BufferedReader getReader(String URLstring) {
     InputStream dataIn; 
     InfoDialog warning;
     urlString = "";
     try{
       try{
         URL url = new URL(URLstring);
         URLConnection connection = url.openConnection();
         BufferedReader ins = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         urlString = URLstring;
         return ins;
       }
       catch (MalformedURLException u){
         System.out.println ("Unable to open URL");
         warning = new InfoDialog("Warning", "Unable to open URL");
         warning.show();
         urlString = "";
         return null;
       }
     }
     catch (IOException io){
       System.out.println ("Can't access the file");
       warning = new InfoDialog("Warning", "Can't access the file");
       warning.show();
       urlString = "";
       return null;
     }
   }
}
