#include "philosopher.h"

Philosopher::Philosopher(QString s, QVector<Fork> *fork, int id) : name(s)
{
    left_fork = false;
    right_fork = false;
    forkNumber = fork;
    idPhil = id;
}

void Philosopher::eat()
{
    QString temp = name + " кушает.";
    Sleep(1000);
    emit(signalAddText(temp));
}

void Philosopher::think()
{
    QString temp = name + " думает.";
    Sleep(1000);
    emit(signalAddText(temp));
}

void Philosopher::takeForks()
{
    if((!(*forkNumber)[idPhil].getIsUsing())&&(!(*forkNumber)[(idPhil+4)%5].getIsUsing()))
    {
        (*forkNumber)[idPhil].take();
        left_fork = true;
        (*forkNumber)[(idPhil+4)%5].take();
        right_fork = true;
        QString temp = name + " взял вилки.";

        emit(signalAddText(temp));
        Sleep(1000);

    }
}

void Philosopher::putForks()
{
    QString temp = name + " положил вилки.";

    emit(signalAddText(temp));

    (*forkNumber)[idPhil].put();
    left_fork = false;

    (*forkNumber)[(idPhil+4)%5].put();
    right_fork = false;

    Sleep(1000);
}

void Philosopher::life()
{
    while(true)
    {
        think();
        takeForks();
        if (left_fork && right_fork)
        {
            eat();
            putForks();

        }
    }
}
