from abjad.cfg._get_last_output import _get_last_output
from abjad.cfg._open_file import _open_file
from abjad.cfg._read_config_file import _read_config_file
import os


def pdf(target = -1):
   '''Call ``pdf( )`` to open PDF output files generated by *Abjad*.

      ::

         abjad> t = Note(0, (1, 4))
         abjad> show(t)

      The input above renders a PDF output file and opens it.

      If you close the PDF output file and want to open it again, \
      call ``pdf( )``.

      ::

         abjad> pdf( )

      Use ``pdf( )`` to open the last PDF output file \
      after it has been closed.

      *  When ``target = -1`` open the last PDF output file.
      *  When ``target = -2`` open the next-to-last PDF output file.
      *  When ``target = -3`` open the next-to-next-to-last PDF output file.
      *  When ``target`` is positive open ``target.pdf``.

      .. note::

         By default, *Abjad* writes *LilyPond* input files
         to the ``~/.abjad/output`` directory. 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( )
      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(ABJADOUPUT, 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
