// Classe Livro

import java.util.concurrent.locks.ReentrantLock;

public class Livro extends ReentrantLock implements Comparable
{
    private int id;
    
    private int timeReading;
    private int readers;
    private int timeToRead;
    private BufferMensagem buffer;

    public Livro(int codigo, int tempoDeLeitura, int quantidadeDeLeitoresSimultaneos, BufferMensagem buffer)
    {
        super();
        this.id = codigo;
        this.timeReading = tempoDeLeitura;
        this.readers = quantidadeDeLeitoresSimultaneos;
        this.timeToRead = 0;
        this.buffer = buffer;
    }

    public boolean emprestar()
    {
        if(this.tryLock())
        {
            this.buffer.mensagem(String.format("O livro " + this.getCodigo() + " foi emprestado ao estudante: " + 
                                                Thread.currentThread().getId() + " \n"));
            return true;
        }
        return false;
    }

    public void devolver()
    {
        this.unlock();
        this.buffer.mensagem(String.format("O livro " + id + " foi devolvido pelo estudante: " + 
                                            Thread.currentThread().getId() + " \n" ));
    }

    public void ler()
    {
        try
        {
            Thread.sleep(timeReading);
            this.timeToRead++;
        } 
        catch (Exception excecao)
        {
            System.out.println(excecao.getMessage());
        }
    }

    public int getCodigo()
    {
        return id;
    }

    public int getTempoDeLeitura()
    {
        return timeReading;
    }

    public int compareTo(Object o)
    {
        int valorDeRetorno = 0;
        if(o instanceof Livro)
        {
            Livro livro = (Livro) o;
            if(livro.getCodigo() == this.getCodigo())
            {
                valorDeRetorno = 1;
            }
        }
        return valorDeRetorno;
    }

    public int getTempoLido()
    {
        return timeToRead;
    }
}
