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

// NOTE: these need to be global now, because the step function needs to edit them.
bool CustomersLeft = true;
int TimePassed = 0;
int NextQueueIndex;

// TODO: define the cashier struct here

// TODO: declare your cashier here as a global variable

// TODO: define the step function here

int main()
{
	// NOTE: CustomerQueue is now a global Variable
	InitCustomerQueue();	
  
	initTimeTable();
	NextQueueIndex = 0;

	// TODO: move this to the cashier struct
	//-----
	int TimeToScan = 0;
	state CurrentState = STATE_ready_for_customer;
 	int CurrentCustomer = 0;
	int CurrentItemIndex;
	//-----

	// NOTE: we change the program to compute ItemsLeft instead of keeping it in a varriable
	while(CustomersLeft)
	{
		// TODO: refactor this code to the step function
		if(CurrentState == STATE_ready_for_item)
		{
			if(CurrentItemIndex < CUSTOMER_ITEM_COUNT)
			{
				item CurrentItem = CustomerQueue[CurrentCustomer].Items[CurrentItemIndex];

				TimeToScan = Time[CurrentItem] + CustomerQueue[CurrentCustomer].PackingSpeed;
				CurrentState = STATE_scanning;
			}
			else
			{
				CurrentState = STATE_ready_for_customer; 
			}
		}
		else if (CurrentState == STATE_scanning)
		{
			TimePassed ++;
			TimeToScan --;

			if (TimeToScan == 0)
			{
				CurrentItemIndex++;
				CurrentState = STATE_ready_for_item;
				printf("Time since start: %ds. Scanned product %d. %d to go.\n",
				       TimePassed, CurrentItemIndex,
				       CUSTOMER_ITEM_COUNT-CurrentItemIndex);
			}

		}
		else
		{
			if(NextQueueIndex < 3)
			{
				CurrentCustomer = NextQueueIndex++;
				CurrentState = STATE_ready_for_item;
				CurrentItemIndex = 0;
				printf("Currently serving customer %d.\n", CurrentCustomer);
			}
			else
			{
				CustomersLeft = false; 
			}
		}
	}
}
