package fsModule;
import java.util.*;
import java.io.*;
import java.net.*;
import utility.*;

public class FileServerHandler extends ServerHandler
{

	Query query = new Query();
	Vector files = new Vector();
	Vector packages = new Vector();
	Vector projects = new Vector();
	FileDataServer fds = null;
	public FileServerHandler()
	{
		fds = new FileDataServer(9050);
		setFiles();
		setProjects();
		setPackages();

	}

	boolean authenticate(AgentIdentity id)
	{
		boolean accept = false;
		String loginName = id.getLoginName();
		int connectionId = id.getId();

		ResultSelect rs = null;
		rs = query.selectQuery("select * from loginStatus where LoginName='"+loginName+"' and ConnectionId="+connectionId);
		if (rs.rowVector.size()!=1)
		{
			accept=false;
			return accept;
		}
		try
		{
			if ( loginName.equals (((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(0)) && connectionId==(Integer.parseInt((String)((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(1))))
				accept=true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return accept;
	}
	public void doThis(Request req, AgentIdentity id)
	{
		if(req.getRequestType().compareTo("Add") == 0)
		{
			AgentIdentity aid = (AgentIdentity)req.getObject();
			boolean accept = authenticate(aid);
			if(accept)
			{
				id= aid;
				Response resAccept = new Response(id,"AddAccepted");
				ServerHeader toBeSentAccept = new ServerHeader(resAccept);
				FileInfo info = new FileInfo(files,packages,projects);
				Response fileInfo = new Response(info,"FileInfo");
				ServerHeader toBeSentInfo = new ServerHeader(fileInfo);
				try
				{
					sendResponse(toBeSentAccept,id.getId());
				}
				catch(Exception e)
				{
					System.out.println("couldn't sent "+ e);
				}
				try
				{
					sendResponse(toBeSentInfo,id.getId());
				}
				catch(Exception e)
				{
					System.out.println("couldn't sent "+ e);
				}
			}
			else
			{
				Response res = new Response(null,"AddRejected");
				ServerHeader toBeSent  = new ServerHeader(res);
				try
				{
					sendResponse(toBeSent,id.getId());
				}
				catch(Exception e)
				{
					System.out.println("couldn't sent "+ e);
				}
			}
		}
		else
		if(req.getRequestType().compareTo("FileRead") == 0)
		{


				AgentIdentity aid = ((FileRead)req.getObject()).id;
				int fileId = ((FileRead)req.getObject()).fileId.intValue();

				ResultSelect rsRead = query.selectQuery("SELECT UserName ,  Time FROM fileRead WHERE FileID ="+fileId);
				//ResultSelect rsDownload = query.selectQuery("SELECT UserName ,  Time FROM fileDownload WHERE FileID ="+fileId);
				Vector fileRead = rsRead.getRowVector();
				//Vector fileDownload = rsDownload.getRowVector();
				ResultSelect rs = query.selectQuery(" select FileName ,Location ,Owner ,PackageName ,ProjectName , Time from file as t1 , package as t2 , project as t3 where FileId ="+fileId+" AND t1.PackageID =t2.PackageID AND t2.ProjectID = t3.ProjectID");

				if (rs.rowVector.size()==1)
				{
					FileResponse fileRes = new FileResponse();
					Properties prop = new Properties();
					String fileName = (String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(1));
					prop.setProperty("FileName",(String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(0)));
					prop.setProperty("Owner",(String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(2)));
					prop.setProperty("PackageName",(String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(3)));
					prop.setProperty("ProjectName",(String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(4)));
					prop.setProperty("Time",(String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(5)));
					fileRes.setFileProperties(prop);
					//fileRes.setFileDownload(fileDownload);
					fileRes.setFileRead(fileRead);
					Response res = new Response(fileRes,"FileResponse");
					//System.out.println(fileName);
					ServerHeader toBeSent = new ServerHeader(res);
					try
					{
						sendResponse(toBeSent,id.getId());
					}
					catch(Exception e)
					{
						System.out.println("cudn't send ");
					}

					boolean success = false;
					try
					{
						success =fds.srvHandler.sendStream(fileName,id.getId());
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
					if(success)
					{
						System.out.println("file req from "+aid.getLoginName()+"for "+fileId);
						System.out.println("send file successfully");
						rs = query.selectQuery("SELECT * FROM fileRead WHERE UserName ='"+aid.getLoginName()+"' AND FileID ="+fileId);
						if (rs.rowVector.size() !=1)
						{
							query.updateQuery("INSERT INTO fileRead VALUES ("+fileId +",'"+aid.getLoginName()+"'"+" ,NOW())");
						}
						if (rs.rowVector.size() ==1)
						{
							query.updateQuery("UPDATE fileRead SET Time = NOW()  WHERE UserName ='"+aid.getLoginName()+"' AND FileID ="+fileId );
						}
					}

				}

		}
		else
		if(req.getRequestType().compareTo("RemoveConnection") == 0)
		{
			RemoveConnection rmc = (RemoveConnection) req.getObject();
			System.out.println("got req of logOff from : "+rmc.id.getLoginName());
			removeConnection(rmc.id);
		}


		else
		if(req.getRequestType().compareTo("FileUpload") == 0)
		{
			FileUpload up = (FileUpload)req.getObject();
			System.out.println("file from :" +up.id.getLoginName());
			int fileId = up.fileId.intValue();
    			int newFileId = 0;
			String fileName = null;
			synchronized (query)
			{
				/*ResultSelect rs = query.selectQuery("SELECT MAX(FileID) FROM file");
				if((String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(0)) == null)
					newFileId = 1;
				else
				{
					try
					{
						newFileId = Integer.parseInt((String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(0)));
						newFileId++;
					}
					catch(Exception e)
					{
						System.out.println("file ID " +e);
					}
				}*/
				fileName = new String("/root/files/file"+fileId);
				System.out.println("saving file to "+fileName);
				 query.updateQuery("UPDATE file set Time = NOW() ,Owner ='"+up.id.getLoginName()+"' WHERE FileID ="+fileId);



			}

			boolean success = false;
			try
			{
				success =fds.srvHandler.readStream(id,fileName);
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			if(success)
			{
				System.out.println("read file successfully");
				ResultSelect rs = query.selectQuery(" select FileName ,PackageName ,ProjectName from file as t1 , package as t2 , project as t3 where FileId ="+fileId+" AND t1.PackageID =t2.PackageID AND t2.ProjectID = t3.ProjectID");
				if(rs.rowVector.size() ==1)
				{
					String send =(String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(2))+"->"+(String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(1))+"->"+(String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(0));
					newFileId = 1;
					Response res = new Response("file uploded :"+send,"Allert");
					ServerHeader toBeSent = new ServerHeader(res);
					try
					{
						broadcast(toBeSent);
					}
					catch(Exception e)
					{
						System.out.println("cudn't send ");
					}
					setFiles();
					FileInfo info = new FileInfo(files,packages,projects);
					Response fileInfo = new Response(info,"FileInfo");
					ServerHeader toBeSentInfo = new ServerHeader(fileInfo);
					try
					{
						broadcast(toBeSentInfo);
					}
					catch(Exception e)
					{
						System.out.println("cudn't send ");
					}
				}
			}
		}

		else
		if(req.getRequestType().compareTo("FileAdd") == 0)
		{
			FileAdd add = (FileAdd)req.getObject();
			int packageId = add.packageId.intValue();
			String fileName = add.fileName;
			System.out.println("file add req from from :" +add.id.getLoginName());
			int newFileId = -1;
    			String newFileName = null;
			boolean success = true;
			synchronized (query)
			{
				ResultSelect rs = query.selectQuery("SELECT MAX(FileID) FROM file");
				if((String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(0)) == null)
					newFileId = 1;
				else
				{
					try
					{
						newFileId = Integer.parseInt((String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(0)));
						newFileId++;
					}
					catch(Exception e)
					{
						success = false;
						System.out.println("fileId " +e);
					}
				}
				if(success)
				{
					newFileName = new String("/root/files/file"+newFileId);
					System.out.println("add file name is "+fileName);
					query.updateQuery("INSERT INTO file values(null, '"+fileName+"' ,"+packageId+",'"+newFileName+"', '"+add.id.getLoginName()+"',NOW())");
				}
			}

			if(success)
			{
				FileAddResponse addRes = new FileAddResponse(newFileId);
				Response res = new Response (addRes,"FileAddResponse");
				ServerHeader toBeSent = new ServerHeader(res);
				success = false;
				try
				{
					success =sendResponse(toBeSent,id.getId());
				}
				catch(Exception e)
				{
					success = false;
					System.out.println("cudn't send file add response :" +e);

				}

			}

		}
		else
			System.out.println(" in doThis method: unknown request"+req.getRequestType());
	}
	void setFiles()
	{

		ResultSelect rs = query.selectQuery("SELECT FileID,FileName,PackageID FROM file ");
		int i=0;
		int j =rs.rowVector.size();
		Properties prop[]= new Properties[j];
		files.removeAllElements();
		for (i =0;i<j;++i)
		{
			//System.out.println((String)((Vector)rs.rowVector.elementAt(i)).elementAt(0)+" "+(String)((Vector)rs.rowVector.elementAt(i)).elementAt(1)+" " +(String)((Vector)rs.rowVector.elementAt(i)).elementAt(2));
			prop[i]= new Properties();
			prop[i].setProperty("FileID",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(0));
			prop[i].setProperty("FileName",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(1));
			prop[i].setProperty("PackageID",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(2));
			files.add(prop[i]);
		}
	}
	void setPackages()
	{
		ResultSelect rs = query.selectQuery("SELECT PackageID,PackageName,ProjectID FROM package ");
		int i=0;
		int j =rs.rowVector.size();
		Properties prop[]= new Properties[j];
		packages.removeAllElements();
		for (i =0;i<j;++i)
		{
			//System.out.println((String)((Vector)rs.rowVector.elementAt(i)).elementAt(0)+" "+(String)((Vector)rs.rowVector.elementAt(i)).elementAt(1)+" " +(String)((Vector)rs.rowVector.elementAt(i)).elementAt(2));
			prop[i]= new Properties();
			prop[i].setProperty("PackageID",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(0));
			prop[i].setProperty("PackageName",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(1));
			prop[i].setProperty("ProjectID",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(2));
			packages.add(prop[i]);
		}
	}

	void setProjects()
	{
		ResultSelect rs = query.selectQuery("SELECT ProjectID,ProjectName FROM project ");
		int i=0;
		int j =rs.rowVector.size();
		Properties prop[]= new Properties[j];
		projects.removeAllElements();
		for (i =0;i<j;++i)
		{
			//System.out.println((String)((Vector)rs.rowVector.elementAt(i)).elementAt(0)+" "+(String)((Vector)rs.rowVector.elementAt(i)).elementAt(1));
			prop[i]= new Properties();
			prop[i].setProperty("ProjectID",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(0));
			prop[i].setProperty("ProjectName",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(1));
			projects.add(prop[i]);
		}
	}

}
