#!/usr/bin/env python
################################################################################
# AUTHOR: KANNAN MASILAMANI
################################################################################
# This python script creates pvd file from list of multiple pvtu files in 
# given directory
################################################################################
import sys
import os
import glob
from tools.functions import *
################################################################################

in_files = None

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--files', help='Input *.pvtu files')
parser.add_argument('--out', help='Output folder')
args = parser.parse_args()

# First look for mandatory files as input.
if not args.files:
  print('''No files to work on provided.

           Please provide the files to process as arguments like:
           treelm/peons/harvest_series.py fileA fileB pre*.lua

           or in the configuration file as a list of comma separated files:
           files: fileA,fileB,pre*.lua

           Note that you can make use of globbing expansions here.

           As there are no files provided, there is nothing to do...
        ''')
  sys.exit(1)

print('Input files: {0}'.format(args.files))

# Now go on with the optional arguments, either provided in the config file,
# or the command line.
# The command line arguments take precedence over settings in the config file.
if args.out:
  out_folder = expanded_path(args.out)

print('Output folder: {0}'.format(out_folder))

# Check if the folder exists. If not -> create
if not os.path.exists(out_folder):
  if args.verbose:
    print('Output folder does not exist. Creating {0}'.format(out_folder))
  os.makedirs(out_folder)

if isinstance(args.files, str):
  infileList = getFileNames(args.files.split(','))
else:
  infileList = getFileNames(args.files)

# Sort files by timestamps, required for proper visit movie files.
# Only add each timestamp once.
filewithtime = []
seen = set()
for iFile in infileList:
  print('Found file {0}'.format(iFile))
  timestamp = float(iFile.split('_t')[1].strip('.pvtu'))

  if timestamp not in seen:
    seen.add(timestamp)
    filewithtime.append( (timestamp, iFile) )

infileList = sorted(filewithtime)

funit = None

iFile_count = 0
# Process each file
for filetime in infileList:
  time  = filetime[0]
  iFile = filetime[1]
  print('Processing file {0}'.format(iFile))

  pvtufile = os.path.basename(iFile.rstrip().split(' ')[-1])
  if iFile_count == 0:
    pvdname = pvtufile.split('_t')
    pvdbase = ''.join(pvdname[0:-1]) + '.pvd'
    pvdfile = os.path.join(out_folder, pvdbase)
    funit = open(pvdfile, 'w')
    writePVDHeader(funit)

  timestr = '{0:e}'.format(time)
  writePVDData(funit, pvtufile, timestr)

  iFile_count = iFile_count + 1


# close pvd file
try:
  writePVDClose(funit)
except:
  print('Could not close pvd unit. Most likely something went wrong. Or no files were provided')

