//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//PIMS: Personal Invstment Management System
//Class : NetLoader
//Use:Downloads the current prices from the net and updates the
//share price database
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

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

public class NetLoader extends Frame implements Runnable{

	private dataRepository DR;
	private int fill=0;
	private String host = "202.87.40.188";
	private String fileName = "stok/nse/pric.xls";
	private int numShares;
	private String shares[][];
	private boolean downloadOption;

	public NetLoader(dataRepository DR, boolean downloadOption){

	   	this.DR = DR;
		this.downloadOption = downloadOption;
	}

	public void run(){
	   try{

	   	setSize(500,90);
		setTitle("Download Prices");
		setBackground(Color.white);
		setVisible(true);

		
		//download the current prices from the net
		if(downloadOption)downloadPrices(host, fileName);

		//toHtml is a program that converts an .xls file to html file that is easier to parse.
		Process P = java.lang.Runtime.getRuntime().exec("./toHTML");
		P.waitFor();

		//parse the html file to get the prices.
		shares = parseFile();
		
		//Update the share price database
		DR.writeSharePrices(numShares, shares);

		setVisible(false);
	   }catch(Exception e){
		System.out.println(e);
	   	e.printStackTrace();
		new Error("Failure to download current prices");
		
		//return;
	   }
	}

	public String downloadPrices(String host,String file_name)throws Exception{

		String result=null;
		String request="";
		String req="http://"+host+"/"+file_name;

	    try{
		Socket soc=new Socket(host,80);

		OutputStream out=soc.getOutputStream();
		InputStream in=soc.getInputStream();

		request="GET "+req+" HTTP/1.0\r\n"+""+"\r\n";

		//writing the request to the given host
		byte buffer[]=request.getBytes();
		out.write(buffer);

		//reading the reply
		FileOutputStream FW = new FileOutputStream("./price.xls");
		byte header[]=new byte[500];
		int head[] = new int[500];
		int c;
		int i=0;
		while(true){//reading the downloded file.
			if(i>=500)break;//reading only the header.
			c=in.read();
			if(c == -1)break;
			header[i]=(byte) c;
			head[i++] = c;
		}
		String temp=new String(header,0,500);

		//read the length of the file.
		int CL = temp.indexOf("Content-Length");
		int index=temp.indexOf("\r\n\r\n");
		int fileLength = Integer.parseInt(temp.substring(CL+16, index));

		int n=Integer.parseInt(temp.substring(9,12));
		if(n==200){//download OK.
			//read the rest of the file and write to the output file.
			for(int k=index+4;k<500;++k)FW.write(head[k]);
			i = 500 - index - 4;
			while(true){//reading the downloded file.
				c=in.read();
				i++;
				fill = (i*300)/fileLength;
				if(i%50 == 0)repaint();
				FW.write(c);
				if(i == fileLength)break;
			}
		}
		in.close();
		out.close();
	    }catch(Exception e){System.out.println(e);}
	    return(result);
	}

	//Shows the progress bar.
	public void paint(Graphics g){
		g.drawRect(100,40,300,30);
		g.fillRect(100,40,fill,30);
		if(fill != 300)
			g.drawString("Download in Progress...", 150, 80);
		else
			g.drawString("Download Complete...", 150, 80);
	}

	//Parses the html file containing the prices in a table and extracts the prices.
	private String[][] parseFile()throws Exception{

		int i;
		int st,end;
		numShares = 0;
		String Line;
		String companyName, price;
		String shares[][] = new String[1000][2];
		FileReader FR = new FileReader("price.html");
		BufferedReader BR = new BufferedReader(FR);

		//Eat away the initial lines of the file.
		for(i=0;i<26;++i){
			BR.readLine();
		}
		while(true){
			Line = BR.readLine();

			if(Line == null)break;

			if(Line.startsWith("<TD ALIGN")){
				//for(i=0;i<1;++i){
					st = Line.indexOf(">");
					end = Line.indexOf("<",st);
					Line = Line.substring(st+1, end);
				//}
				companyName = Line;

				for(i=0;i<3;++i)BR.readLine();//eat the intermediate lines.
				Line = BR.readLine();//read the price

				//for(i=0;i<1;++i){
					st = Line.indexOf(">");
					end = Line.indexOf("<",st);
					Line = Line.substring(st+1, end);
				//}
				price = Line;

				shares[numShares][0] = companyName;
				shares[numShares][1] = price;
				numShares++;
			}
		}
		return(shares);
	}
}
