#from abjad.cfg.cfg import ABJADOUTPUT
from abjad.cfg._read_config_file import _read_config_file
from abjad.cfg._get_last_output import _get_last_output
import os


## TODO: Open operating-specific text editor instead of vi. ##

def ly(target = -1):
   r'''Call ``ly( )`` to ``vi`` *LilyPond* input files generated by *Abjad*.

      *  When ``target = -1`` open the most recent *LilyPond* input file.
      *  When ``target = -2`` open the next-to-last such file.
      *  When ``target`` is positive, open ``target.ly``

      ::

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

      ::

         % Abjad revision 2162
         % 2009-05-31 14:29

         \version "2.12.2"
         \include "english.ly"
         \include "/Path/to/abjad/trunk/abjad/scm/abjad.scm"

         {
            c'4
         }      

      Exit ``vi`` in the usual way with ``:q`` or equivalent.'''

   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_ly = os.path.join(ABJADOUTPUT, target_str + '.ly')
      else:
         print 'Target LilyPond input file does not exist.'
   elif isinstance(target, int) and 0 <= target:
      target_str = '%04d' % target
      target_ly = os.path.join(ABJADOUTPUT, target_str + '.ly')
   elif isinstance(target, str):
      target_ly = os.path.join(ABJADOUTPUT, target)
   else:
      raise ValueError('can not get target LilyPond input from %s.' % target)

   if os.stat(target_ly):
      os.system('vi %s' % target_ly)
   else:
      print 'Target LilyPond input file %s does not exist.' % target_ly
