package com.ytarzimanov.utils.net.tcp.server;

import java.util.Calendar;
import java.util.Date;

import com.ytarzimanov.utils.net.tcp.Connection;
import com.ytarzimanov.utils.net.tcp.Const;
import com.ytarzimanov.utils.net.tcp.CommandHandler;
import com.ytarzimanov.utils.net.tcp.Connection.OnUpdateListener;

public class Session extends Thread{
		  protected Connection connection;
		  protected CommandHandler handler;
		  protected Date date = null;
		  private static int activeSessionCount = 0;
		  
		  
		  public Session(CommandHandler handler){
			  this.handler = handler;
			  setName(String.format("tcp-ss(%s)", getCommand()));
		  }
		  
		  
		  public static int getActiveSessionCount(){
			  return activeSessionCount;
		  }
		  	  
		  synchronized public String getCommand(){
			return handler.getCommand();
		  }
		  
		  synchronized public void setConnection(Connection connection){
			this.connection = connection;
			connection.setOnUpdateListener(new OnUpdateListener(){

				@Override
				public void update() {
					date = Calendar.getInstance().getTime();
				}});
		  }
		  
		  synchronized public void stopSession(){
			  handler.stop();
			  connection.close();
		  }
		  
		  synchronized public Boolean isExpired(){
			  long diff_sec = (Calendar.getInstance().getTimeInMillis() - date.getTime()) / 1000;
			  return diff_sec > 5;
		  }
		  		  
		  @Override
		  public void run() {
			  date = Calendar.getInstance().getTime();
			  Const.addTrace(Session.class, String.format(Const.FORMAT_LOG_MSG5, getCommand()));
			  activeSessionCount++;
			  handler.execute(connection);  
			  if (connection.receive().equals(Const.CLOSE_SESSION));
			    connection.send(String.format(Const.FORMAT_SESSION_CLOSED_SUCCESSFULY, handler.getCommand()));
			  activeSessionCount--;
			  Const.addTrace(Session.class, String.format(Const.FORMAT_LOG_MSG6, getCommand()));
			  connection.close();
		  }
}
