/* File: use_queues.c
 * 
 * Implements a queue.  This program abstracts the queue datatype and places
 * it in a different file.
 */

#include <iostream>
using namespace std;
#include <string>
#include <new>
#include "queues.h"               // the interface to the queue datatype

#define QUEUE_A_SIZE 10           // the size of queue "A"
#define QUEUE_B_SIZE 8            // the size of queue "B"

void out_of_memory(void);         // called if we run out of memory

int main(void)
{
    string command;               // buffer the user command
    string queue_name;            // and desired queue
    int  element;                 // a queue element
    Queue A(QUEUE_A_SIZE);        // queue A
    Queue B(QUEUE_B_SIZE);        // queue B
    Queue *queue;                 // a pointer to the current queue

    set_new_handler(out_of_memory);   // what to do on memory error

    while (cin >> command)            // while more input ...
    {
        if (cin >> queue_name)        // after the command comes the queue
        {
            if (queue_name == "A")    // set the current queue
                queue = &A;
            else if (queue_name == "B")
                queue = &B;
            else                      // illegal queue ...
            {
                cout << "Invalid queue.\n";
                continue;
            }
        }
        else                          // cin fails, so no more input
            break;

        try
        {
            if (command == "remove")             // if user enters "remove"
                cout << queue->remove() << '\n';
            else if (command == "peek")          // if user enters "peek"
                cout << queue->peek() << '\n'; 
            else if (command == "insert")        // if user enters "insert"
            {
                if (cin >> element)              // get the element
                {
                    queue->insert(element);      // and add it to the queue
                    cout << "Ok.\n";
                }
                else                             // if we don't read an int
                {                                // print error and reset cin
                    cout << "Nothing to insert\n";
                    cin.clear();
                }
            }
            else
                cout << "Illegal command\n";
        }
        catch (Queue::Queue_empty)               // catch the queue errors
        {
            cout << "Queue is empty.\n";
        }
        catch (Queue::Queue_full)
        {
            cout << "Queue is full.\n";
        }
    }

    return 0;
}

/* 
 * out_of_memory() - what we should do on a memory error
 */
void out_of_memory(void)
{
    cerr << "Out of memory\n.Exiting...\n";
    exit(0);
}


