#!/usr/bin/env python
import argparse
import sys
import pythapi
import configparser
import os
import urllib3
import json

class pythapiCLI(object):

    def __init__(self):

        urllib3.disable_warnings()

        try:
            config = configparser.ConfigParser()
            with open(os.path.expanduser('~') + '/.pythapi/config') as f:
                config.read_file(f)
            self.endpoint = pythapi.Connect(config['default']['endpoint'], config['default']['base_url'])
            if config['auth']['authentication']:
                self.endpoint.authorization = config['auth']['auth_key']
        except IOError:
            sys.exit("Error: Unable to read config file.")
        
        parser = argparse.ArgumentParser(
            usage='''pythapi <command> [<args>]

The most commonly used HTTP methods are:
   get     HTTP GET Request
   post    HTTP POST Request
   put     HTTP PUT Request
   delete  HTTP DELETE Request
''')
        parser.add_argument('method', help='HTTP method to run')
        # parse_args defaults to [1:] for args, but you need to
        # exclude the rest of the args too, or validation will fail
        args = parser.parse_args(sys.argv[1:2])
        if not hasattr(self, args.method):
            print('Unrecognized command')
            parser.print_help()
            exit(1)
        # use dispatch pattern to invoke method with same name
        getattr(self, args.method)()

    def get(self):
        parser = argparse.ArgumentParser(
            description='HTTP GET Request')
        # prefixing the argument with -- means it's optional
        parser.add_argument('path', help="The path to the API call")
        # now that we're inside a subcommand, ignore the first
        # TWO argvs, ie the command (git) and the subcommand (commit)
        args = parser.parse_args(sys.argv[2:])
        print(self.endpoint.get(args.path))

    def post(self):
        parser = argparse.ArgumentParser(
            description='HTTP POST Request')
        # prefixing the argument with -- means it's optional
        parser.add_argument('path', help="The path to the API call")
        parser.add_argument('body', help="Filename containing the content of the body")
        # now that we're inside a subcommand, ignore the first
        # TWO argvs, ie the command (git) and the subcommand (commit)
        args = parser.parse_args(sys.argv[2:])

        try:
            f=open(args.body, "r")
            data = json.loads(f.read())
            print(self.endpoint.post(args.path, data))
        except IOError:
            sys.exit("Error: Unable to read body file.")

    def put(self):
        parser = argparse.ArgumentParser(
            description='HTTP PUT Request')
        # prefixing the argument with -- means it's optional
        parser.add_argument('path', help="The path to the API call")
        parser.add_argument('body', help="Filename containing the content of the body")
        # now that we're inside a subcommand, ignore the first
        # TWO argvs, ie the command (git) and the subcommand (commit)
        args = parser.parse_args(sys.argv[2:])
        
        try:
            f=open(args.body, "r")
            data = json.loads(f.read())
            print(self.endpoint.put(args.path, data))
        except IOError:
            sys.exit("Error: Unable to read body file.")

    def delete(self):
        parser = argparse.ArgumentParser(
            description='HTTP DELETE Request')
        # prefixing the argument with -- means it's optional
        parser.add_argument('path', help="The path to the API call")
        # now that we're inside a subcommand, ignore the first
        # TWO argvs, ie the command (git) and the subcommand (commit)
        args = parser.parse_args(sys.argv[2:])
        print(self.endpoint.delete(args.path))

if __name__ == '__main__':
    pythapiCLI()