#!/usr/bin/env python
# encoding: utf-8
#
# @Author: Jon Holtzman
# @Date: March 2018
# @Filename: mkgrid
# @License: BSD 3-Clause
# @Copyright: Jon Holtzman


from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import argparse
import os
import sys
import subprocess
import datetime
import time
import matplotlib
matplotlib.use('Agg')

from apogee.speclib import sample
from apogee.speclib import synth

if __name__ == '__main__' :

    parser = argparse.ArgumentParser(
        prog=os.path.basename(sys.argv[0]),
        description='Makes a synthetic spectral grid')

    parser.add_argument('name', type=str, help='Sample name file')
    parser.add_argument('--gridclass', type=str, help='Grid class for sample', default=None)
    parser.add_argument('--nsamp', type=int, help='Number of samples per HR point', default=1)
    parser.add_argument('--nosynth', help='Create sample but not syntheses',action="store_true")
    parser.add_argument("--done")
    parser.add_argument("--host")
    args=parser.parse_args()

    now = datetime.datetime.now()
    start = time.time()
    print ("Start: ",now.strftime("%Y-%m-%d %H:%M:%S"))

    os.environ['ISOCHRONE_DIR']=os.environ['HOME']+'/isochrones/'
    sample.sample(name=args.name,gridclass=args.gridclass,emlim=[0.,0.],nsamp=args.nsamp,rot=True)
    if not args.nosynth : synth.mksynth(args.name,threads=32)

    now = datetime.datetime.now()
    print ("End: ",now.strftime("%Y-%m-%d %H:%M:%S"))
    print("elapsed: ",time.time()-start)

    if args.done is not None :
        subprocess.call(['setdone',args.done])
        try: 
            subprocess.call(['setdone',done])
        except: pass
        print('host', args.host)
        if args.host is not None :
            try: os.remove(args.done+'.'+args.host)
            except: pass

