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

public class NbServerHandler extends ServerHandler
{

	Query query = new Query();
	Vector notices = new Vector();
	NbDataServer nbds = null;

	public NbServerHandler()
	{
		nbds = new NbDataServer(7050);
		setNotices();

	}

	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);
				NoticeInfo info = new NoticeInfo(notices);
				Response resInfo = new Response(info,"NoticeInfo");
				ServerHeader toBeSentInfo= new ServerHeader(resInfo);
				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("NoticeRequest") == 0)
		{


				AgentIdentity aid = ((NoticeRequest)req.getObject()).id;
				int noticeId = ((NoticeRequest)req.getObject()).noticeId.intValue();

				ResultSelect rsel = query.selectQuery("SELECT UserName ,  DateReading FROM noticeRead WHERE NoticeID ="+noticeId);
				Vector noticeRead = rsel.getRowVector();

				ResultSelect rs = query.selectQuery("select * from notice where NoticeId = "+noticeId);

				if (rs.rowVector.size()==1)
				{
					NoticeResponse noticeRes = new NoticeResponse();
					String fileName = (String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(5));
					noticeRes.setNoticeId((String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(0)));
					noticeRes.setDisplayer((String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(1)));
					noticeRes.setDatePosting((String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(2)));
					noticeRes.setNoticeTitle((String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(3)));
					noticeRes.setDateRemoving((String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(4)));
					noticeRes.setNoticeRead(noticeRead);
					Response res = new Response(noticeRes,"NoticeResponse");
					//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 =nbds.srvHandler.sendStream(fileName,id.getId());
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
					if(success)
					{
						System.out.println("notice req from "+aid.getLoginName()+" for "+noticeId);
						System.out.println("send file successfully");
						rs = query.selectQuery("SELECT * FROM noticeRead WHERE UserName ='"+aid.getLoginName()+"' AND NoticeID ="+noticeId);
						if (rs.rowVector.size() !=1)
						{
							query.updateQuery("INSERT INTO noticeRead VALUES ('"+aid.getLoginName()+"' ,"+noticeId+" ,CURRENT_DATE)");
						}
					}

				}

		}
		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("NoticeUpload") == 0)
		{
			NoticeUpload up = (NoticeUpload)req.getObject();
			System.out.println("notice from :" +up.id.getLoginName()+"notice title :"+up.noticeName +"date of removal :"+up.dateRemoval);
			int newNoticeId = -1;
    			String fileName = null;
			synchronized (query)
			{
				ResultSelect rs = query.selectQuery("SELECT MAX(NoticeID) FROM notice");
				if((String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(0)) == null)
					newNoticeId = 1;
				else
				{
					try
					{
						newNoticeId = Integer.parseInt((String)(((java.util.Vector)rs.rowVector.elementAt(0)).elementAt(0)));
						newNoticeId++;
					}
					catch(Exception e)
					{
						System.out.println("noticeId " +e);
					}
				}
				//System.out.println("new noticeId is "+newNoticeId);
				fileName = new String("/root/notices/notice"+newNoticeId+".txt");
				query.updateQuery("INSERT INTO notice values(null, '"+up.id.getLoginName()+"',CURRENT_DATE,'"+up.noticeName +"','"+up.dateRemoval+"','"+fileName+"')");
			}

			boolean success = false;
			try
			{
				success =nbds.srvHandler.readStream(id,fileName);
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			if(success)
			{
				System.out.println("read notice successfully");
				setNotices();
				NoticeInfo info = new NoticeInfo(notices);
				Response resInfo = new Response(info,"NoticeInfo");
				ServerHeader toBeSentInfo= new ServerHeader(resInfo);
				try
				{
					broadcast(toBeSentInfo);
				}
				catch(Exception e)
				{
					System.out.println("couldn't sent "+ e);
				}
				Response resAllert = new Response("New Notice Added","Allert");
				ServerHeader toBeSentAllert= new ServerHeader(resAllert);
				try
				{
					broadcast(toBeSentAllert);
				}
				catch(Exception e)
				{
					System.out.println("couldn't sent "+ e);
				}

			}
		}

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

		ResultSelect rsdel =query.selectQuery("SELECT NoticeID  FROM notice WHERE DateRemoving < CURRENT_DATE");
		int i =0;
		for(i=0;i<rsdel.rowVector.size();++i)
		{
			query.updateQuery("DELETE FROM noticeRead WHERE NoticeID ="+(String)((Vector)rsdel.rowVector.elementAt(i)).elementAt(0));
		}
		int k=query.updateQuery("DELETE FROM notice WHERE DateRemoving < CURRENT_DATE");
		System.out.println("No. of Deleted notices : "+k);
		ResultSelect rs = query.selectQuery("SELECT NoticeID,Displayer,DatePosting,NoticeTitle FROM notice ORDER BY DatePosting DESC");
		int j =rs.rowVector.size();
		Properties prop[]= new Properties[j];
		notices.removeAllElements();
		for (i =0;i<j;++i)
		{
			prop[i]= new Properties();
			prop[i].setProperty("NoticeId",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(0));
			prop[i].setProperty("Displayer",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(1));
			prop[i].setProperty("DatePosting",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(2));
			prop[i].setProperty("NoticeTitle",(String)((Vector)rs.rowVector.elementAt(i)).elementAt(3));
			notices.add(prop[i]);
		}
	}



}
