#!/usr/bin/env python3

import sys 
import os 
import argparse 
import time

from fieldops.fieldopsconn import FieldOpsConn

args = None
parser = None
import json

fo = FieldOpsConn()

#fieldops packages list 




#fieldops post packages/pa-firmware  -f <file> -h -u <user> -p <password> -v <version> -t <track> -d <descriptio> 

def init_args():
    global parser
    parser = argparse.ArgumentParser('FieldOps API tool')
    parser.add_argument('command', type=str, help='Command to execute [get, download, upload, token, backup]', nargs='*')
    parser.add_argument('-f', '--file', type=str, help='File to upload')
    parser.add_argument('-s', '--host', type=str, help='Host to connect to, with optional port (host:port)')
    parser.add_argument('-u', '--user', type=str, help='User to connect with')
    parser.add_argument('-a', '--auth', type=str, help='Auth Token')
    parser.add_argument('-p', '--password', type=str, help='Password to connect with')
    parser.add_argument('-t', '--track', type=str, help='Track to upload to', default='release')
    parser.add_argument('-r', '--release-notes', type=str, help='release notes for new version', default='')
    parser.add_argument('-v', '--version', type=str, help='Version of the file')
    parser.add_argument('-o', '--output', type=str, help='Output file')

def main():
    global parser 
    global args 

    init_args()
    args = parser.parse_args()

    if args.host is None:
        raise Exception('Host not set')

    if args.auth is not None:
        fo.connect(host=args.host,token=args.auth)
    elif args.host is not None and args.user is not None and args.password is not None:
        fo.connect(host=args.host, email=args.user, password=args.password)
    else :
        raise Exception('Requires credentials (email/password or token)')

    resp = None

    if args.command[0] == 'get':
        path = args.command[1]
        resp = fo.get(path)

        out = json.dumps(resp.json(), indent=4)
        print(out)

    elif args.command[0] == 'token':

        if len(args.command) == 1:
            print(fo.token)
        else: 
            print(fo.getToken(args.command[1]))
    
    elif args.command[0] == 'backup':
        outPath = ''
        filename = fo.post('/backups/create', {} ).json()['name']
        
        print(str(filename))
        if len(args.command) == 1:
            outPath = filename
        else:
            outPath = args.command[1]

        #wait for backup to complete
        retry_count = 0
        print('Waiting for backup to complete')
        backupPath = '/backups/' + filename.replace(".gz", "")
        while fo.get(backupPath).status_code != 200:
            retry_count += 1
            if retry_count > 10:
                break
            time.sleep(1)

        if retry_count < 10:
            resp = fo.download( backupPath, outPath)
            print(outPath)
        else:
            print('Backup failed')
            sys.exit(1)
    
    elif args.command[0] == 'restore':

        if args.file is None:
            raise Exception('File not specified')
        
        resp = fo.post('/backups/restore', args.file, '', '', '')
        print(resp.json())

    elif args.command[0] == 'download':
        path = args.command[1]
        outpath = ''
        if args.output is not None:
            outpath = args.output
        resp = fo.download(path, outpath)

        print(resp)
    
    elif args.command[0] == 'upload':
        path = args.command[1]
        if args.file is None:
            raise Exception('File not specified')
        if args.version is None:
            raise Exception('Version not specified')

        resp = fo.upload(path, args.file,args.version, args.track, args.release_notes)
        print(resp.json())
    
    elif args.command[0] == 'list':
        path = args.command[1]
        resp = fo.get(path)

        obj = resp.json()
        if type(obj) is list:
            for item in obj:

                if 'name' in item:
                    print("{0} \t\t\t[{1}]".format(item['name'], item['handle']))
                elif 'id' in item:
                    print(item['id'])
                elif 'deviceId' in item:
                    print(item['deviceId'])

    if resp is not None:
        
        if resp.status_code >= 200 and resp.status_code < 300:
            print('Success')
            sys.exit(0)
        else:
            print('Failed')
            print(resp.json())
            sys.exit(1)


        





if __name__ == '__main__':
    main()

