#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr  4 10:35:02 2020

@author: JKH

This function takes a directory where there is a list file where lines represent
input_file_2020*.txt names and it outputs another list file where names
are the *.tgz files on ccycle

"""

import os
import datetime as dt

curr_dir = os.getcwd()
os.chdir('../python_subs')
import egi_tgz_name as etgzn

os.chdir(curr_dir)



def make_ccycle_tgz_list(submit_dir):
  """
  Main function. Takes input directory that contains list of input file names
  and writes an output file with the *.tgz file names
  
  submit_dir='/home/osboxes/research/tccon/ggg_devel/models/gnd/infiles/submitted/'
  """
  
  list_infl_sbmt = submit_dir + 'submitted_infiles.lst'
  list_cc_names = submit_dir + 'ccycle_tgz_names.lst'
  with open(list_infl_sbmt, 'r') as fid:
      raw_lst_txt = fid.readlines() #
  
  raw_lst_txt = [pymod_inname.rstrip() for pymod_inname in raw_lst_txt] #remove trailing newline characters
  
  
  out_name_lst = [None]*len(raw_lst_txt) #list for output names
  for i1, pymod_inname in enumerate(raw_lst_txt):
      prsd_input = read_input_2020(pymod_inname)
      out_name_lst[i1] = prsd_input
      out_name_lst[i1] = etgzn.make_egi_tar_file_name(prsd_input['site_id'], 
                  prsd_input['lat'], prsd_input['lon'], prsd_input['start_date'])
      
  ### Write names to a list
  with open(list_cc_names, 'w') as fileID:
    for outline_i1 in out_name_lst: #over each name
      fileID.write(outline_i1 + '\n')

  return list_cc_names



def read_input_2020(in_fname):
  """
  Read contents of an input_file_2020*.txt file and save results into a 
  dictionary
  """
  out = {} #pre-allocated output
  with open(in_fname, 'r') as fid:
    raw_infile = fid.readlines()
  
  raw_infile = [in_line.rstrip() for in_line in raw_infile] #remove end of line new-line characters
  
  for i1, in_line in enumerate(raw_infile):
    splt_line = in_line.split('=')
    if len(splt_line) != 2:
      raise ValueError('Each line in file ' + '%s' % in_fname + 
                       " expected to have one '=' but line " + '%d' % i1 +
                       ' has ' + '%d' % int(len(splt_line)-1) )
    
    if splt_line[0] in ['lat', 'lon']: #convert to list of floats
      out[splt_line[0]] = [float(lval) for lval in splt_line[1].split(',')]
    
    elif splt_line[0] == 'site_id': #convert to a list
      out[splt_line[0]] = splt_line[1].split(',')
    
    elif splt_line[0] == 'start_date': #convert to datetime
      out[splt_line[0]] = dt.datetime(int(splt_line[1][0:4]), int(splt_line[1][4:6]), int(splt_line[1][6:8]) )
    
    else: #everything else...
      out[splt_line[0]] = splt_line[1]
  
  return out










#with open(????, 'w') as fid:


















