#include "teller.h"
#include "customer.h"
#include <queue>
#include <iostream>
#include <string>
#include <iomanip>
#include <limits.h>
#include "marketsim.h"
static int Teller_id=0;

Teller::Teller()
{
	id=Teller_id++;
	free=true;
	current_customer=0;
	total_number_of_items_this=0;
	total_waiting_time_this=0;
	total_free_time_this=0;
	total_number_of_customers_this=0;

	total_number_of_items=0;
	total_waiting_time=0;
	total_free_time=0;
	total_number_of_customers=0;
	time_transaction_ends=0;
}

bool Teller::is_free() const{return free;}


void Teller::start_transaction(Customer* j,unsigned long t,Market_Simulation& ms)
{
	total_free_time_this+=(t-time_transaction_ends);
	total_free_time+=(t-time_transaction_ends);
	free=false;
	current_customer=j;
	
	long waiting_time=t-j->get_arrival_time();
	total_waiting_time_this+=waiting_time;
	total_waiting_time+=waiting_time;
	time_transaction_ends=t+j->get_processing_time();
	
	total_number_of_customers_this++;
	total_number_of_customers++;
	total_number_of_items_this+=(*j).get_item_number();
	total_number_of_items+=(*j).get_item_number();

	event* next_event=new Teller_Becomes_Free(time_transaction_ends,this,ms);
	ms.scheduleEvent(next_event);
}

void Teller::end_transaction(unsigned long t)
{
	free = true;
	delete current_customer;
}

void Teller::print_local_stats(Market_Simulation& ms,std::string st)
{
	std::cout<<st << std::setw(5)<<id;
	
	if(total_number_of_customers_this !=0)
	{
		std::cout<<std::setw(12)<<
		   (float)total_waiting_time_this/total_number_of_customers_this;
		std::cout<<std::setw(12)<<total_number_of_customers_this*3600/ms.get_max_time();
		std::cout<<std::setw(12)<<total_number_of_items_this*3600/ms.get_max_time();
		std::cout<<std::setw(12)<<
			(float)total_free_time_this/total_number_of_customers_this;
		std::cout<<std::setw(12)<<total_free_time_this;
	}
	else
	{
		std::cout<<std::setw(12)<<"NAN";
		std::cout<<std::setw(12)<<0;
		std::cout<<std::setw(12)<<0;	
		std::cout<<std::setw(12)<<"NAN";
		std::cout<<std::setw(12)<<ms.get_max_time();
	}
	std::cout<<'\n';
}

void Teller::print_qlobal_stats(Market_Simulation& ms)
{
	std::cout<<'\n'<<std::setw(8)<<"total";
	std::cout<<std::setw(12)<<
		(float)total_waiting_time/total_number_of_customers;
	std::cout<<std::setw(12)<<total_number_of_customers*3600/ms.get_max_time();
	std::cout<<std::setw(12)<<total_number_of_items*3600/ms.get_max_time();
	std::cout<<std::setw(12)<<
			(float)total_free_time/total_number_of_customers;

	std::cout<<std::setw(12)<<total_free_time;
	std::cout<<'\n';
}

long Teller::total_number_of_items;
long Teller::total_free_time;
int Teller::total_number_of_customers;
long Teller::total_waiting_time;
