#!python
import sys, os
from glob import glob
import argparse, logging
from datetime import datetime
import pandas as pd
from calc_pe import mainPE
from calc_pe.utils import printPE

parser = argparse.ArgumentParser(
  description="Program to compute the parasitic energy from single component isotherms",
  formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
        "adsorbent_name",
        help="Name of the adsorbent framework.")
parser.add_argument(
        "gasin",
        choices=["coal", "ng", "air"],
        help="Compositon of the input gas mixture, i.e. post-combustion\n" +
             "flue gas from coal or natural gas, or air.")
parser.add_argument(
        "-rho",
        type=float,
        dest="rho",
        default=None,
        help="Density of the adsorbent framework (kg/m3).\n" +
             "(default: value readen from datapath/adsorbent_name/rho.csv)")
parser.add_argument(
        "-vf",
        type=float,
        dest="vf",
        default=0.35,
        help="Void fraction of the adsorbent bed.\n" +
             "(default: 0.35)")
parser.add_argument(
        "-process",
        dest="process",
        default="TPSA",
        choices=["TPSA", "TSA", "PSA"],
        help="Process used for the CO2 sequestration.\n" +
             "(default: TPSA)")
parser.add_argument(
        "-cp",
        type=float,
        dest="cp",
        default=None,
        help="Choice for the heat adsorption of the adsorbent:\n" +
             "for nanoporous materials it should range between 761.0\n" +
             "and 1210.0 J/kg/K.\n" +
             "(default: readen from datapath/adsorbent_name/cp.csv if present,\n" +
             "          otherwise 985.0 J/kg/K, the average)")
parser.add_argument(
        "-yd",
        type=float,
        dest="yd",
        default=0.99,
        help="Required output CO2 fraction at desorption.\n" +
             "(default: 0.99)")
parser.add_argument(
        "-eleff",
        dest="eleff",
        default="carnot",
        choices=["carnot", "linear"],
        help="Method to compute the electricity conversion efficiency.\n" +
             "(default: carnot)")
parser.add_argument(
        "-opt",
        dest="opt",
        default="PE",
        choices=["PE", "Q", "WC", "pur"],
        help="Optimizes for the optimal condition: lowest PE or Q,\n" +
             "or highest working capacity (WC) or pur(ity).\n" +
             "(default: PE)")
parser.add_argument(
        "-datapath",
        type=str,
        dest="datapath",
        default="./",
        help="Path containing the isotherms in .csv format.\n" +
             "(default: ./)")
parser.add_argument(
       "-l",
       "--log",
       action = "store_true",
       help="Write .log file for debug")
args = parser.parse_args()
if args.log:
  # Set up the debug .log file
  now = datetime.now().isoformat()
  logfile = 'calcPE_%s_%s.log' % (args.adsorbent_name, now)
  logging.basicConfig(
    filename=logfile, format='%(message)s', level=logging.DEBUG
  )
logging.debug(args)

# Convert varables into the arguments to feed the mainPE function
if args.rho != None:
    rho = args.rho
elif os.path.exists(os.path.join(args.datapath, args.adsorbent_name, "rho.csv")):
    with open(os.path.join(args.datapath, args.adsorbent_name, "rho.csv")) as f:
        rho = float(f.readline().strip()) #density in kg/m3
else:
    sys.exit('WARNING: density of the framework unknown!')

if args.cp != None:
    cp = args.cp
elif os.path.exists(os.path.join(args.datapath, args.adsorbent_name, "cp.csv")):
    with open(os.path.join(args.datapath, args.adsorbent_name, "cp.csv")) as f:
      cp = float(f.readline().strip()) #cp in J/kg/K
else:
    cp = 948.0 #average for MOFs


T_iso={}
iso_df={}
for m in ['CO_2','N_2']:
  iso_dir = os.path.join(args.datapath, args.adsorbent_name, m) # dir containing isotherms
  iso_files = glob(os.path.join(iso_dir, '*.csv'))
  if len(iso_files) == 0:
      sys.exit('WARNING: no isotherm found in {}!'.format(iso_dir))
  elif len(iso_files) > 1:
      sys.exit('WARNING: more than one file in {}; keep only one!'.format(iso_dir))
  else:
      iso_file = iso_files[0] # .csv files for the isotherms
      T_iso[m] = int(os.path.splitext(os.path.basename(iso_file))[0][:-1]) # read temperature of the isotherm from the filename
      iso_df[m] = pd.read_csv(iso_file, sep=' ') #values of the isotherm

# Run the main function, and print results
res = mainPE(gasin=args.gasin,
             rho=rho,
             vf=args.vf,
             process=args.process,
             cp=cp,
             yd=args.yd,
             eleff=args.eleff,
             opt=args.opt,
             T_iso=T_iso,
             iso_df=iso_df,
            )
printPE(args.adsorbent_name,res)
