package fsModule;
import utility.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.tree.*;
import javax.swing.border.BevelBorder;
public class FsClientHandler extends ClientHandler
{

	JDesktopPane desktop = null;
	AgentIdentity id ;
	public Gui g = null;
	public GuiFile gf =null;
	boolean loggedIn = false;
	Vector files = null;
	Vector projects = null;
	Vector packages = null;
	public FsClientHandler()
	{

  		g =new Gui();

	}
	public FsClientHandler(InputStream in, OutputStream out,JDesktopPane desktop)
	{
		super(in,out);
		this.desktop = desktop;
		g =new Gui();

	}


	public void doThis(Response res)
	{
		if (loggedIn)
		{
			if( res.getResponseType().compareTo("FileResponse") == 0)
			{

				FileResponse fileRes = (FileResponse)res.getObject();
				//System.out.println(noticeRes.noticeId + noticeRes.displayer+noticeRes.datePosting+noticeRes.noticeTitle);
				System.out.println("Got notice Response");
				StringBuffer buffer =null;
				FsDataAgent fsda =new FsDataAgent();
				try
				{
					fsda.cliHandler.readStream();
				}
				catch(Exception e)
				{
					System.out.println("cudn't read file from server");
				}
				System.out.println("waiting for sream reading to be finished ");
				while(!fsda.cliHandler.readingComplete)
				{

				}
				System.out.println("reading fininshed getting buffer .");
				buffer = fsda.cliHandler.getBuffer();
				gf =  new GuiFile(buffer,fileRes);
				desktop.add(gf,JLayeredPane.PALETTE_LAYER);

			}
			else
			if( res.getResponseType().compareTo("FileInfo") == 0)
			{
				FileInfo info = (FileInfo)res.getObject();
				files = info.files;
				packages = info.packages;
				projects = info.projects;
				g.removeAll();
				g.repaint();
				g.buildGui();
				g.repaint();

			}
			else if( res.getResponseType().compareTo("Allert") == 0)
			{
				String got = (String)res.getObject();
				JOptionPane.showMessageDialog(null, got);
			}
			else
			if( res.getResponseType().compareTo("FileAddResponse") == 0)
			{
				FileAddResponse far = (FileAddResponse)res.getObject();
				int fileId = far.fileId.intValue();
				uploadFile(""+fileId);
			}
			else
				System.out.println("in doThis method: Unknown response"+res.getResponseType());
		}
	}



	public boolean addFile()
	{
		desktop.add(new AddFileGui(),JLayeredPane.PALETTE_LAYER);
		return false;
	}
	public boolean addPackage(String packageName,int projectId)
	{
		return false;
	}
	public boolean addProject(String projectName)
	{
		return false;
	}

	public void openFile(String fileIdString)
	{
		int fileId = -1;
		try
		{
			fileId = Integer.parseInt(fileIdString);
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, " Cudn't Open file " +e);
			fileId=-1;
		}
		if(fileId != -1)
		{
			FileRead fr = new FileRead(fileId,id);
			Request req = new Request(fr,"FileRead");
			ClientHeader toBeSent = new ClientHeader(req);
			try
			{
				sendRequest(toBeSent);
			}
			catch(Exception e)
			{
				System.out.println("Cudn't send fileRead request :"+e);
			}
		}
	}
	
	public void uploadFile(String fileIdString)
	{
		int fileId = -1;
		try
		{
			fileId = Integer.parseInt(fileIdString);
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, " Cudn't Open file " +e);
			fileId=-1;
		}
  		if(fileId != -1)
		{
			JFileChooser chooser = new JFileChooser();
			chooser.setApproveButtonText("Send");
			chooser.setApproveButtonToolTipText("Send file");
			int state = chooser.showDialog(null,"send");
			File file = chooser.getSelectedFile();
			boolean success = false;
			if(file != null && state == JFileChooser.APPROVE_OPTION )
			{
				success =sendFile(file,fileId);
			}
		}
	}


	public boolean sendFile(File file,int fileId)
	{
		FsDataAgent fsda =new FsDataAgent();
		boolean success = false;
		FileUpload up = new FileUpload(fileId,id);
		Request req = new Request(up,"FileUpload");
		ClientHeader toBeSent = new ClientHeader(req);
		try
		{
				sendRequest(toBeSent);
		}
		catch(Exception e)
		{
				e.printStackTrace();
		}
		System.out.println("sending file  to server ");
		try
		{
			success = fsda.cliHandler.sendStream(file);
		}
		catch(Exception e)
		{
			System.out.println("cudn't send file from server");
			success =false;
		}
		return success;
	}
	public void setAgentId (AgentIdentity id)
	{
		this.id = id;
	}
	public class Gui extends JPanel
	{

		Hashtable hashPackage = new Hashtable();
		Hashtable hashProject = new Hashtable();
		public Gui()
		{

		}
		void buildGui()
		{
			DefaultMutableTreeNode top = new DefaultMutableTreeNode( new MyNode("-1", "Projects"));
			DefaultTreeModel model = new DefaultTreeModel(top);
			final JTree  tree =new JTree(model);
			hashPackage.clear();
			hashProject.clear();
			int i=0;int j=projects.size();
			DefaultMutableTreeNode node[] = new DefaultMutableTreeNode[j];
			for(i=0;i<j;++i)
			{
				Properties prop = (Properties)projects.elementAt(i);
				node[i]= new DefaultMutableTreeNode(new MyNode("-1",prop.getProperty("ProjectName")));
				hashProject.put(prop.getProperty("ProjectID"),node[i]);
				top.add(node[i]);
			}

			j=packages.size();
			node = new DefaultMutableTreeNode[j];
			DefaultMutableTreeNode parent = new DefaultMutableTreeNode();
			for(i=0;i<j;++i)
			{
				Properties prop = (Properties)packages.elementAt(i);
				node[i]= new DefaultMutableTreeNode(new MyNode("-1",prop.getProperty("PackageName")));
				hashPackage.put(prop.getProperty("PackageID"),node[i]);
				parent = (DefaultMutableTreeNode)hashProject.get(prop.getProperty("ProjectID"));
				parent.add(node[i]);
			}
			j=files.size();
			node = new DefaultMutableTreeNode[j];
			for(i=0;i<j;++i)
			{
				Properties prop = (Properties)files.elementAt(i);
				node[i]= new DefaultMutableTreeNode(new MyNode(prop.getProperty("FileID"),prop.getProperty("FileName")));
				parent = (DefaultMutableTreeNode)hashPackage.get(prop.getProperty("PackageID"));
				parent.add(node[i]);

			}
			add(tree);
			tree.addTreeSelectionListener(new TreeSelectionListener()
			{
				public void valueChanged(TreeSelectionEvent e)
				{
					DefaultMutableTreeNode node =(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
           				if(node != null)
					{
						if(node.isLeaf())
           					{
							MyNode nd = (MyNode)node.getUserObject();
        						String fileId = nd.getId();
							Object[] possibleValues = { "Open", "Upload" };
 							Object selectedValue = JOptionPane.showInputDialog(null,"Choose one", "Input",JOptionPane.INFORMATION_MESSAGE, null,
							possibleValues, possibleValues[0]);
							if(selectedValue !=null)
							{
								if(((String)(selectedValue)).compareTo("Open") == 0)
									openFile(fileId);
								if(((String)(selectedValue)).compareTo("Upload") == 0)
									uploadFile(fileId);
							}
						}
						else
							return;
					}
				}
			});
			DefaultTreeCellRenderer renderer = new
      			DefaultTreeCellRenderer();
  		  	renderer.setOpenIcon(new ImageIcon("opened.gif"));
    			renderer.setClosedIcon(new ImageIcon("closed.gif"));
   			renderer.setLeafIcon(new ImageIcon("leaf.gif"));
    			tree.setCellRenderer(renderer);

    			tree.setShowsRootHandles(true);
    			tree.setEditable(false);
    			tree.setVisible(true);


		}
		public void showGui()
		{
			System.out.println("showing Gui");
			loggedIn = true;
			setVisible(true);

		}



	}
	public class GuiFile extends JInternalFrame
	{

		String buffer = null;
		FileResponse fileRes = null;
		Vector fileRead = null;
		//Vector fileDownload = null;
		Properties fileProp = null;
		public GuiFile(StringBuffer buffer,FileResponse fileRes)
		{
			super("File",false,true,false,true);
			this.buffer = String.valueOf(buffer);
			this.fileRes =fileRes;
			fileRead = fileRes.fileRead;
		//	fileDownload = fileRes.fileDownload;
			fileProp = fileRes.fileProperties;
			buildGui();

		}
		void buildGui()
		{
			Container con = getContentPane();
			JTextArea textArea = new JTextArea(buffer);
			textArea.setEditable(false);
			textArea.setVisible(true);
			JScrollPane jsp = new JScrollPane(textArea);
			JPanel jp = new JPanel();

			JScrollPane jspComment = new JScrollPane(jp);//
			jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS));
			jp.setVisible(true);

			JPanel p = new JPanel();
			p.setLayout(new BoxLayout(p,BoxLayout.X_AXIS));
			p.add(new JLabel((String)fileProp.getProperty("FileName")));
			p.setBorder(new BevelBorder(BevelBorder.RAISED));
			jp.add(p);

			JPanel p1 = new JPanel();
			p1.setLayout(new BoxLayout(p1,BoxLayout.X_AXIS));
			p1.add(new JLabel("Owner"));
			JTextField t1 = new JTextField((String)fileProp.getProperty("Owner"));
			t1.setBorder(new BevelBorder(BevelBorder.RAISED));
			t1.setEditable(false);
			p1.add(Box.createHorizontalStrut(70));
			p1.add(t1);
			jp.add(p1);

			JPanel p2 = new JPanel();
			p2.setLayout(new BoxLayout(p2,BoxLayout.X_AXIS));
			p2.add(new JLabel("Package"));
			JTextField t2 = new JTextField((String)fileProp.getProperty("PackageName"));
			t2.setEditable(false);
			t2.setBorder(new BevelBorder(BevelBorder.RAISED));
			p2.add(Box.createHorizontalStrut(60));
			p2.add(t2);
			jp.add(p2);

			JPanel p3 = new JPanel();
			p3.setLayout(new BoxLayout(p3,BoxLayout.X_AXIS));
			p3.add(new JLabel("Project"));
			JTextField t3 = new JTextField((String)fileProp.getProperty("ProjectName"));
			t3.setEditable(false);
			t3.setBorder(new BevelBorder(BevelBorder.RAISED));
			p3.add(Box.createHorizontalStrut(70));
			p3.add(t3);
			jp.add(p3);

			int i =0;
			int j= fileRead.size();
			JPanel read = new JPanel();
			if(j!=0)
			{

				read.setLayout(new GridLayout(j+1,3));

				read.add(new JLabel("File is read by"));
				for(i=0;i<2;++i)
					read.add(Box.createHorizontalStrut(0));
				for(i=0;i<j;++i)
				{
					read.add(new JLabel((String)(((java.util.Vector)fileRead.elementAt(i)).elementAt(0))));
					read.add(new JLabel("on"));
					read.add(new JLabel((String)(((java.util.Vector)fileRead.elementAt(i)).elementAt(1))));
				}
			}
			jp.add(read);//



			JTabbedPane jtp = new JTabbedPane();
			jtp.addTab("File",jsp);
			jtp.addTab("Comments",jspComment);
			con.add(jtp);
			setVisible(true);
			setBounds(190,65,425,220);
			setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
		}
	}

	public class MyNode
	{
		protected String   id;
		protected String name;
		public MyNode(String id, String name)
		{
    			this.id = id;
			this.name = name;
  		}
		public String getId()
		{
			return id;
		}
		public String getName()
		{
			return name;
		}
		public String toString()
		{
			return name;
		}
	}

	public class AddFileGui extends JInternalFrame
	{
		Hashtable hashProject = new Hashtable();
		String packageId = null;
		JTextField fileField = new JTextField(15);
		public AddFileGui()
		{
			super("File",false,true,false,true);
			buildGui();
		}
		void buildGui()
		{
			Container con = getContentPane();
			DefaultMutableTreeNode top = new DefaultMutableTreeNode( new MyNode("-1", "Projects"));
			DefaultTreeModel model = new DefaultTreeModel(top);
			final JTree  tree =new JTree(model);
			hashProject.clear();
			int i=0;int j=projects.size();
			DefaultMutableTreeNode node[] = new DefaultMutableTreeNode[j];
			for(i=0;i<j;++i)
			{
				Properties prop = (Properties)projects.elementAt(i);
				node[i]= new DefaultMutableTreeNode(new MyNode("-1",prop.getProperty("ProjectName")));
				hashProject.put(prop.getProperty("ProjectID"),node[i]);
				top.add(node[i]);
			}

			j=packages.size();
			node = new DefaultMutableTreeNode[j];
			DefaultMutableTreeNode parent = new DefaultMutableTreeNode();
			for(i=0;i<j;++i)
			{
				Properties prop = (Properties)packages.elementAt(i);
				node[i]= new DefaultMutableTreeNode(new MyNode((String)prop.getProperty("PackageID"),prop.getProperty("PackageName")));
				//hashPackage.put(prop.getProperty("PackageID"),node[i]);
				parent = (DefaultMutableTreeNode)hashProject.get(prop.getProperty("ProjectID"));
				parent.add(node[i]);
			}

			DefaultTreeCellRenderer renderer = new
      			DefaultTreeCellRenderer();
  		  	renderer.setOpenIcon(new ImageIcon("opened.gif"));
    			renderer.setClosedIcon(new ImageIcon("closed.gif"));
   			renderer.setLeafIcon(new ImageIcon("leaf.gif"));
    			tree.setCellRenderer(renderer);

    			tree.addTreeSelectionListener(new TreeSelectionListener()
			{
				public void valueChanged(TreeSelectionEvent e)
				{
					DefaultMutableTreeNode node =(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
           				if(node != null)
					{
						if(node.isLeaf())
           					{
							MyNode nd = (MyNode)node.getUserObject();
        						packageId = nd.getId();
						//	JOptionPane.showMessageDialog(null,nd.getId());
						}
						else
							return;
					}
				}
			});


			tree.setShowsRootHandles(true);
    			tree.setEditable(false);
    			tree.setVisible(true);
			JScrollPane jsp = new JScrollPane(tree);
			con.setLayout(new BorderLayout());
			con.add(jsp,BorderLayout.CENTER);
			
			JLabel label = new JLabel("File Name");

			JButton button = new JButton("Add");
			button.addActionListener(new ButtonHandler());
			JPanel panelContainer  = new JPanel();
			panelContainer.setLayout(new FlowLayout());
			panelContainer.add(label);
			panelContainer.add(fileField);
			panelContainer.add(button);
			con.add(panelContainer,BorderLayout.SOUTH);

			setVisible(true);
			setBounds(190,65,425,220);
			setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
		}
		public class ButtonHandler implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				if(packageId == null)
				{
					JOptionPane.showMessageDialog(null,"Package not seleceted","error",JOptionPane.ERROR_MESSAGE);
					return;
				}
				String fileName = fileField.getText();
				if (fileName.length() > 0)
				{
					int pId =0;
					boolean success =true;
					try
					{
						pId =Integer.parseInt(packageId);
					}
					catch(Exception ex)
					{
						JOptionPane.showMessageDialog(null,"cudn't send "+ex);
						success = false;
					}
					if(success)
					{
						FileAdd fa = new FileAdd(pId,fileName,id);
						Request req = new Request(fa,"FileAdd");
						ClientHeader toBeSent = new ClientHeader(req);
						try
						{
							sendRequest(toBeSent);
						}
						catch(Exception ex)
						{
							System.out.println("Cudn't send file Add req");
						}
					}
					dispose();
				}
			}
		}
	}
}

