from abjad.cfg._read_config_file import _read_config_file
from abjad.tools.iotools._open_file import _open_file
from abjad.tools.iotools.get_last_output_file_name import get_last_output_file_name
import os


def pdf(target = -1):
    '''Open the last PDF generated by Abjad with ``iotools.pdf()``.

    Open the next-to-last PDF generated by Abjad with ``iotools.pdf(-2)``.

    Return none.

    Abjad writes PDFs to the ``~/.abjad/output`` directory by default.

    You may change this by setting the ``abjad_output`` variable in the ``config.py`` file.
    '''

    ABJADOUTPUT = _read_config_file()['abjad_output']
    if isinstance(target, int) and target < 0:
        last_lilypond = get_last_output_file_name()
        if last_lilypond:
            last_number = last_lilypond.replace('.ly', '')
            target_number = int(last_number) + (target + 1)
            target_str = '%04d' % target_number
            target_pdf = os.path.join(ABJADOUTPUT, target_str + '.pdf')
        else:
            print 'Target PDF does not exist.'
    elif isinstance(target, int) and 0 <= target:
        target_str = '%04d' % target
        target_pdf = os.path.join(ABJADOUTPUT, target_str + '.pdf')
    elif isinstance(target, str):
        target_pdf = os.path.join(ABJADOUTPUT, target)
    else:
        raise ValueError('can not get target pdf name from %s.' % target)

    if os.stat(target_pdf):
        pdf_viewer = _read_config_file()['pdf_viewer']
        _open_file(target_pdf, pdf_viewer)
    else:
        print 'Target PDF %s does not exist.' % target_pdf
