#!/usr/bin/env python3
import argparse
from chibchas.tools import main, time
import getpass
import tempfile
import shutil
import sys
#__file__='.........'
parser = argparse.ArgumentParser(description='Chibchas Institulac')
parser.add_argument('--gdrive_path', type=str,required=True,
                    help='Google drive mount point path to save the data')
parser.add_argument('--max_tries', type=int, default=10,
                    help='max tries in case of error downloading')
parser.add_argument('--headless', type=bool, default=True,
                    help='enable of disable the browser for helium.')
parser.add_argument('--debug', type=bool, default=False,
                    help='Allows to print messages for debugging')
parser.add_argument('--start', type=int, default=0,
                    help='Grupo donde empieza')
parser.add_argument('--end', type=int, default=None,
                    help='Grupo donde termina')

args = parser.parse_args()

if __name__=='__main__':
    user=input('Usuario: ')
    password=getpass.getpass('Contraseña: ')

    if args.debug:
        print(user," ",password)
    tmp_path = tempfile.gettempdir()+"/chibchas/"+user
    print("Saving data on temporal folder {}".format(tmp_path))
    max_tries=args.max_tries
    for n in range(max_tries):
        try:
            #Set end=None to reach the last element
            LOGIN = main(user,password,DIR=tmp_path,CHECKPOINT=True,headless=args.headless,start=args.start,end=args.end,start_time=time.time())
            if not LOGIN:
                break
            
            shutil.copytree(tmp_path, args.gdrive_path, dirs_exist_ok=True)
            break
        except:
            print("Unexpected error:", sys.exc_info()[0])
            print('='*80)
            print(f'try {n}/{max_tries}')
            print('='*80)
