#!/usr/bin/env python
from __future__ import print_function

import argparse
import os
import sys
import subprocess
import textwrap

import urbandict


def paged_output(string):
    pager = os.getenv("PAGER")
    if not pager:
        # no PAGER set, print stuff as is
        print(string)
        return

    pager_args = []

    if pager == 'less':
        pager_args += ['-r', '-F', '-X']

    p = subprocess.Popen([pager] + pager_args, stdin=subprocess.PIPE)
    p.stdin.write(string.encode('utf-8'))
    p.stdin.close()
    p.wait()


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', dest='use_pager', action='store_false',
            help='do not use PAGER for output')
    parser.add_argument('-r', dest='random', action='store_true',
            help='pull random definition')
    parser.add_argument('term', nargs='?')

    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()

    if args.term:
        translations = urbandict.define(term=args.term)
    elif args.random:
        translations = urbandict.define(term=urbandict.TermTypeRandom())
    else:
        print("You need to either specifiy term "
                "or -r for random definition")
        sys.exit(1)

    output = []

    for index in range(len(translations)):
        if output:
            output += ['\n']
        output += ["%s. %s" % (index + 1, translations[index]['word'])]
        output += ['\n'.join(textwrap.wrap(
                translations[index]['def'],
                initial_indent='  ',
                subsequent_indent='  ')
                )
            ]

        if translations[index]['example'] != '':
            output += [("\n  Examples:\n")]
            output += [('\n'.join(textwrap.wrap(
                    translations[index]['example'],
                    initial_indent='  * ',
                    subsequent_indent=' ' * 4)
                    ))]
            category = translations[index]['category']
            if category != 'unknown':
                output += ["\n  Category: {}".format(category)]
        output += ['\n']

    output_string = ''.join(output)

    if args.use_pager:
        paged_output(output_string)
    else:
        print(output_string)
