#include <stdio.h>
#include <stdbool.h>
#include "supermarket.h"

int FinishedCashiers = 0;
int TimePassed = 0;
int NextQueueIndex;

typedef struct
{
  state CurrentState;
  int CurrentCustomer;
  int CurrentItemIndex;
  
  int TimeToScan;
}cashier;

// TODO: Change this number to 2 after you changed the step function
#define CASHIER_COUNT 1

// TODO: Changes this to an array of 2 cashiers
cashier Cashier = {STATE_ready_for_customer, 0, 0, 0};

// TODO: Changes this to use the index of the cashier 
void step(int Index)
{
	if(Cashier.CurrentState == STATE_ready_for_item)
	{
		if(Cashier.CurrentItemIndex < CUSTOMER_ITEM_COUNT)
		{
			item CurrentItem = CustomerQueue[Cashier.CurrentCustomer].Items[Cashier.CurrentItemIndex];
			Cashier.TimeToScan = Time[CurrentItem] + CustomerQueue[Cashier.CurrentCustomer].PackingSpeed;
			Cashier.CurrentState = STATE_scanning;
		}
		else
		{
			Cashier.CurrentState = STATE_ready_for_customer; 
		}
	}
	else if (Cashier.CurrentState == STATE_scanning)
	{
		Cashier.TimeToScan --;
			if (Cashier.TimeToScan == 0)
		{
		    Cashier.CurrentItemIndex++;
			Cashier.CurrentState = STATE_ready_for_item;
			printf("Time since start: %ds. Cashier %d scanned product %d. %d to go.\n", 
			       TimePassed, Index, Cashier.CurrentItemIndex,
			       CUSTOMER_ITEM_COUNT-Cashier.CurrentItemIndex);
		}
	}
	else if (Cashier.CurrentState == STATE_ready_for_customer)
	{
		if(NextQueueIndex < 3)
		{
			Cashier.CurrentCustomer = NextQueueIndex++;
			Cashier.CurrentState = STATE_ready_for_item;
			Cashier.CurrentItemIndex = 0;
			printf("Cashier %d currently serving customer %d.\n", Index, Cashier.CurrentCustomer);
		}
		else
		{
			// NOTE: Counting up when Cashier is done and there is no more
			// customer to serve
			FinishedCashiers++;

			// NOTE: we added a State for when the cashier is done
			Cashier.CurrentState = STATE_finished;
		}
	}
}

int main()
{
	InitCustomerQueue();	
  
	initTimeTable();
	NextQueueIndex = 0;

	// NOTE: we now need to wait until all cashiers are done
	while(FinishedCashiers < CASHIER_COUNT)
	{
		// TODO: loop over all cashiers
		step(0);

		//---------------------------------

		// NOTE: this gives us slightly diffrent numbers,
		// because we are now also counting state changes.
		// You could change that. It just would make the program more complex.
		TimePassed ++;
	}
}
