#!/usr/bin/env python
# encoding: utf-8
#
# @Author: Jon Holtzman
# @Date: March 2018
# @Filename: pca
# @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 datetime
import time
import os
import sys
import subprocess
import matplotlib
matplotlib.use('Agg')
import pdb

from apogee.speclib import pca
from apogee.aspcap import ferre

if __name__ == '__main__' :

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

    parser.add_argument("planfile", type=str, help='Plan file')
    parser.add_argument("--dir")
    parser.add_argument("--test", help='reduce dims?',action="store_true")
    parser.add_argument("--writeraw", help='write uncompressed file?',action="store_true")
    parser.add_argument("--rawsynth", help='use raw synthesis file?',action="store_true")
    parser.add_argument("--incremental", help='use incremental PCA?',action="store_true")
    parser.add_argument("--piece",nargs='+',type=int)
    parser.add_argument("--pcas",nargs='+',type=int)
    parser.add_argument("--digits",type=int,help='digits to use for file names',default=2)
    parser.add_argument("--py2",action="store_true",help='use Python 2-style rounding for file names')
    parser.add_argument("--threads",type=int,default=4)
    parser.add_argument("--flag",default='11111')
    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"))
    if args.pcas is not None : pcas = tuple(args.pcas)
    else : pcas = None
    pca.pca(args.planfile,pcas=pcas,dir=args.dir,test=args.test,writeraw=args.writeraw,
            incremental=args.incremental,threads=args.threads,rawsynth=args.rawsynth,piece=args.piece,
            digits=args.digits,py2=args.py2)
    now = datetime.datetime.now()
    print ("End: ",now.strftime("%Y-%m-%d %H:%M:%S"))
    print("elapsed: ",time.time()-start)

    # test setup
    #pca.test(args.planfile)

    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
