# -*- encoding: utf-8 -*-
import os


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

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

    Returns 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.
    '''
    from abjad import abjad_configuration
    from abjad.tools import iotools

    ABJADOUTPUT = abjad_configuration['abjad_output']
    if isinstance(target, int) and target < 0:
        last_lilypond_file_name = iotools.get_last_output_file_name()
        if last_lilypond_file_name:
            result = os.path.splitext(last_lilypond_file_name)
            file_name_root, extension = result
            last_number = file_name_root
            target_number = int(last_number) + (target + 1)
            target_str = '%04d' % target_number
            target_pdf = os.path.join(ABJADOUTPUT, target_str + '.pdf')
        else:
            message = 'Target PDF does not exist.'
            print message
    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:
        message = 'can not get target pdf name from {}.'.format(target)
        raise ValueError(message)

    if os.stat(target_pdf):
        pdf_viewer = abjad_configuration['pdf_viewer']
        iotools.open_file(target_pdf, pdf_viewer)
    else:
        message = 'Target PDF {} does not exist.'.format(target_pdf)
        print message
