import time
import os
import sys
import generator
from random import randint


if __name__ == '__main__':
  ''' arguments
  argv[1] : accounts file to use
  argv[2] : master accounts file to use
  argv[3] : new accounts file location
  argv[4] : new master accounts file location
  '''

  accounts_file = sys.argv[1]
  ma_file = sys.argv[2]
  new_accounts_file = sys.argv[3]
  new_ma_file = sys.argv[4]

  # open master accounts file, parse
  master_file = open(ma_file, 'r')
  master = master_file.readlines()
  master_file.close()  

  files_to_merge = []
  sessions = 0
  session = 0 
  unique_ident = int(round(time.time() * 1000))

  print("\n--- starting frontend sessions ---")
  # if master file is empty, start the session by creating accounts
  if (len(master) == 0):
    transactions = generator.create_accounts_session()
    new_name = "transactions_{}_{}".format(session, unique_ident)
    os.rename(transactions, new_name)
    transactions = new_name
    out = "summary_{}_{}".format(session, unique_ident)
    os.system("simbank {} {} < {}".format(accounts_file, out, transactions))
    print("### summary file saved to {} ###".format(out))
    files_to_merge.append(out)
  else:
    # master file is not empty, create accounts
    # reads in the master file for account information and
    # use this information to generate session input automatically
    accounts = {}
    for line in master:
      cmd = line.split()
      account = int(cmd[0])
      balance = int(cmd[1])
      name = ' '.join(cmd[2:])
      accounts[account] = (balance, name)
      sessions = randint(3, 5)
 
  while (session < sessions):
    # run simbank with an autogenerated session
    transactions = generator.create_transaction_file(accounts)
    new_name = "transactions_{}_{}".format(session, unique_ident)
    os.rename(transactions, new_name)
    transactions = new_name
    out = "summary_{}_{}".format(session, unique_ident)
    os.system("simbank {} {} < {}".format(accounts_file, out, transactions))
    print("### summary file saved to {} ###".format(out))
    files_to_merge.append(out)
    session = session + 1

  print("\n--- merging summary files ---")
  # merge all summary files
  merged = []
  for i in range(len(files_to_merge)):
    f = open(files_to_merge[i], 'r')
    cmds = f.readlines()
    f.close()
    if (i != len(files_to_merge) - 1):
      # this is to ignore the last ES line until the last file
      merged += cmds[:-1]
    else:
      merged += cmds
  
  merged_transactions = "merged_transactions_{}".format(unique_ident)
  f = open(merged_transactions, 'w')
  for cmd in merged:
    f.write("{}".format(cmd))
  f.close()
  print("### merged file saved to {} ###".format(merged_transactions))

  print("\n--- starting backend session ---")
  
  # run the backend office with the generated merged transaction summary file
  os.system("backoffice {} {} {} {}".format(ma_file, merged_transactions, new_ma_file, new_accounts_file))
