#Dont invoke interpreter here - let ccp4mg JobControl find the right python
#/usr/bin/python
import os
import sys
import os
import re

#Intercept -help command before trying to load movie

if sys.argv.count('-help') or  sys.argv.count('-h'):
  print """
  CCP4mg utility to compile movies
  
  -help             Print this help
  -dir dirname      Compulsary input: directory containing image files
  -master filename  Name of movie preferences file 
  -scene [n [m ..]] List of scenes to be processed
  -first            First image in scene to be compiled
  -last             Last image in scene to be compiled
  -job_id           Job id - used in tracking the process
  -ext              File extension of output file (mpg/gif/avi)
  -encoder          Encoder program (convert/mencoder/ffmpeg)
  -merge            Merge multiple scenes
  
  For a movie called 'foo' CCP4mg creates a directory 'foo.ccp4mg_presentation'.  This directory contains subdirectories for the scenes which are called
  'scene_00001', scene_00002', etc..  Each scene directory contains
  screenshot images which are named 'frame_000001.png' ,'frame_000002.png' etc..  
  compile_movie converts the screenshots to a movie file for each scene - the
  file is called something like 'scene_nnnnn/movie.gif'.
  With the -merge option the movies from two or more scenes are merged to
  give a file 'foo.ccp4mg_presentation/movie_nnnnn_mmmmm.gif'.
  Note: To run this utility requires the presentation module
  (..ccp4mg/python/ui/presentation.py) to be on the PYTHONPATH.
  """
  
  sys.exit()
  
try:
  from presentation import *
except:
  # Somehow the path was not set properly, try looking where we expect them to be.
  try:
    sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__),"..","util")))
    sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__),"..","pygl")))
    sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__),"..","mgapp")))
    sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__),"..","mmut")))
    sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__),"..","mmdb","src")))
    sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__),"..","surface")))
    sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__),"..","python","ui")))
    sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__),"..","lib")))
    from presentation import *
  except:
    print "Failed to load presentation module !!!"

#-------------------------------------------------------------------------
def unpickle_movie(file):
#-------------------------------------------------------------------------
  import pickle
  import os
  if not os.path.exists(file):
    return [1,None]
  else:
    try:
      errcode = 2
      f = open(file,'r')
      errcode = 3
      pars = pickle.load(f)
      errcode = 4
      f.close()
    except:
      return [errcode,None]
      
  if pars:
    return [0,pars]
  else:
    return [5,None]

#--------------------------------------------------------------------------
def compile_movie():
#--------------------------------------------------------------------------    
  import re
  import os

  # Initialise params
  movie_dir = ''
  master_file = ''
  scene_list = []
  set_range = 0
  first =1
  last =0
  html_template = ''
  html_file = ''
  ext = 'gif'
  encoder = 'convert'
  merge = 0
  no_compile = 0
  
  # Read command line args
  input_params = {}
  i=1
  while i < len(sys.argv):
    if re.match('-d',sys.argv[i]):
      i=i+1
      movie_dir = sys.argv[i]
    elif re.match('-me',sys.argv[i]):
      merge = 1
    elif re.match('-no',sys.argv[i]):
      no_compile = 1
    elif re.match('-m',sys.argv[i]):
      i=i+1
      master_file = sys.argv[i]
    elif re.match('-ext',sys.argv[i]):
      i=i+1
      ext = sys.argv[i]
    elif re.match('-en',sys.argv[i]):
      i=i+1
      encoder = sys.argv[i]
    elif re.match('-so',sys.argv[i]):
      i=i+1
      socket = int(sys.argv[i])
    elif re.match('-scene',sys.argv[i]):
      while i+1 < len(sys.argv) and sys.argv[i+1][0] != '-':
        i = i+1
        scene_list.append(sys.argv[i])
    elif re.match('-fi',sys.argv[i]):
      i=i+1
      first = sys.argv[i]
      set_range = 1
    elif re.match('-l',sys.argv[i]):
      i=i+1
      last = sys.argv[i]
      set_range = 1
    elif re.match('-pl',sys.argv[i]):
      play = 1
      first_movie_file = ''
    elif re.match('-fo',sys.argv[i]):
      i = i + 1
      ext =  sys.argv[i]
    elif re.match('-h',sys.argv[i]):
      if i+1 < len(sys.argv) and  not re.match('-', sys.argv[i+1]):
        i=i+1
        html_file = sys.argv[i]
      else:
        html_file =  os.path.join(os.environ["CCP4_MG"],'data','movie_template.html')
    elif len(sys.argv[i]) and sys.argv[i][0] == '-' and len(sys.argv)>i+1:
      input_params[sys.argv[i][1:]] = sys.argv[i+1]
      i = i + 1
    i = i + 1

  #print "compile_movie scene_list,input_params",scene_list,input_params
  import mg_ex_utility
  ex_ut = mg_ex_utility.mg_ex_utility()
  
  # No movie_dir -> no hope
  if not movie_dir:
    print "ERROR in CCP4mg compile movie: no movie directory"
    ex_ut.WriteLog(status="FAILED in compile_movie: no movie directory" )
    return
  elif not os.path.exists(movie_dir) or not os.path.isdir(movie_dir):   
    print "ERROR in CCP4mg compile movie: movie directory "+movie_dir+" does not exist"
    ex_ut.WriteLog(status="FAILED in compile_movie:  movie directory "+movie_dir+" does not exist")
    return

  # Try guessing the master file
  if not master_file:
    master_file = re.sub('_dir','',movie_dir)
    if not os.path.exists(master_file) or not os.path.isfile(master_file):
      master_file = ''
      
  if master_file:
    rv,params = unpickle_movie(master_file)
    if rv:
      print "ERROR in CCP4mg compile movie: unable to read movie master file "+ master_file+ "Error code:",rv
      ex_ut.WriteLog(status="FAILED in compile_movie: unable to read movie master file "+ master_file )
      return
  else:
    # No master_file -> wing it
    params = {} 

  movie0 = presentation(params=params,master_dir=movie_dir)

  #print "compile_movie params",params
  #print "compile_movie input_params",input_params

  if html_file:
    if params.has_key('frame_size'):   
      height,width = params['frame_size']
    else:
      height,width = [400,400]
    try:
      f = open(html_file,'r')
      html_template = f.read()
      f.close()
    except:
      print "ERROR compiling movie, could not read html template file:\n",html_file

  
  # Compile the individual scenes

  if not no_compile:

    status,movie_file = movie0.compile(scene_list=scene_list, \
       ext=ext,encoder=encoder,preferences=input_params)
    if status != 0:
      # movie_file is the error message
      #print movie_file
      ex_ut.WriteLog(status='FAILED '+movie_file)
      return

  if merge and len(scene_list)>1:
    status,movie_file= movie0.merge_movies(scene_list=scene_list,overwrite=1,ext=ext,encoder=encoder,preferences=input_params)
  if  status != 0:
    ex_ut.WriteLog(status='FAILED '+movie_file)
    return
 
  ex_ut.WriteLog(status='FINISHED')

#-----------------------------------------------------------------------
def make_html_page ( movie_dir ='', html_template='', scene = '' , \
                    movie_file = '',height=400,width=400 ):
#-----------------------------------------------------------------------
  html = re.sub('%GIF_FILE%','"'+movie_file+'"',html_template)

  html = re.sub('%HEIGHT%',str(height),html)
  html = re.sub('%WIDTH%',str(width),html)

  html = re.sub('%NEXT_PAGE%','"page_'+str(scene+1)+'.html"',html)

  return [0,html]
  
#----------------------------------------------------------------------
# This is 'main'
#----------------------------------------------------------------------
print 'into compile_movie'
'''
if sys.platform=='win32':
  import utils
  utils.redirectOutput('compile_movie')
'''
compile_movie()
#if sys.platform == 'win32':  sys.stdout.close()
sys.exit()
