#!/usr/bin/env python3

import os
import sys
import json
import logging
import argparse
import subprocess
import webbrowser

from urllib import parse, request


__VERSION__ = '0.4'

URLS = {
    'new': ('POST', 'http://linkode.org/api/1/linkodes/'),
    'create-child': ('POST', 'http://linkode.org/api/1/linkodes/{linkode_id}'),
    'get': ('GET', 'http://linkode.org/api/1/linkodes/{linkode_id}/'),
}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Paste a text on linkode.org')

    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument('-p', '--parent', type=str,
                        help='linkode id of its parent')
    group.add_argument('-g', '--get', type=str,
                        help='linkode id to get is parent to this new one')

    parser.add_argument('-i', '--input', type=str,
                        help='text file to be pasted on linkode.org')
    parser.add_argument('-t', '--type', type=str,
                        help='the type of the content (plain text, Python, diff, C, etc.)',
                        default='plain text')
    parser.add_argument('-o', '--open',
                        action='store_true',
                        help='open the default browser with the link'),
    parser.add_argument('-r', '--revision', type=int,
                        default=1,
                        help='the revision number of the node that is parent to this new one')
    parser.add_argument('-v', '--verbose',
                        action='store_true',
                        help='show all the debug information')
    parser.add_argument('--version',
                        action='store_true',
                        help='show the version and exit')

    data = {}
    method, url = URLS['new']

    args = parser.parse_args()

    if args.verbose:
        logging.basicConfig(
            format='%(levelname)s:%(asctime)s:%(name)s:%(message)s',
            level=logging.DEBUG)

    if args.version:
        print(__VERSION__)
        sys.exit(0)

    if args.input:
        if os.path.exists(args.input):
            with open(args.input, 'rb') as fh:
                data['content'] = fh.read()
        else:
            print('The file doesn\'t exists.')
    elif not args.get:
        # check if there is data on stdin
        if sys.stdin.isatty():
            parser.print_help()
            sys.exit(0)

        data['content'] = sys.stdin.read()

    data['text_type'] = args.type

    if args.parent:
        method, url = URLS['create-child']
        url = url.format(linkode_id=args.parent)

    if args.revision:
        if args.get:
            print('Ignoring -g / --get argument')
        data['parent'] = args.revision

    if args.get:
        if args.revision:
            print('Ignoring -r / --revision argument')
        method, url = URLS['get']
        url = url.format(linkode_id=args.get)


    logging.debug('DATA: %s', data)
    logging.debug('URL: %s', url)
    logging.debug('METHOD: %s', method)

    raw = parse.urlencode(data).encode('ascii')
    if method == 'POST':
        response = request.urlopen(url, data=raw)
    else:
        response = request.urlopen(url)
    raw = response.read()
    linkode_data = json.loads(raw.decode('utf8'))

    linkode_url = 'http://linkode.org/{}'.format(linkode_data['linkode_id'])
    print(linkode_url)


    try:
        output = subprocess.check_output(['which', 'xclip']) \
                        .decode('utf-8') \
                        .strip()
        os.system('echo {0} | {1} -selection clipboard'\
                  .format(linkode_url, output)
              )
        print('URL copied to clipboard')
    except subprocess.CalledProcessError:
        logging.info('You can install "xclip" to copy the URL to the clipboard')
        
    if args.open:
        webbrowser.open(linkode_url)
