#!/usr/bin/python
# -*- coding: utf-8 -*-
import argparse

from pyzeef import Zeef, __version__


def color_text(text, color):
    COLORS = dict(
        green=32,
        yellow=33,
        red=31,
        magenta=35,
    )
    color_text = u"\033[{}m{}\033[0m"
    return color_text.format(COLORS[color], text)


def get_parser():
    parser = argparse.ArgumentParser(description='ZEEF API Command line')
    parser.add_argument('-t', '--token', help='API Token', action='store')
    parser.add_argument('--pages', help='My ZEEF Pages', action='store_true')
    parser.add_argument('-s', '--scratchpad', help='My ZEEF Scratchpad',
                        action='store_true')
    parser.add_argument('-p', type=int, help='ZEEF Page Summary')
    parser.add_argument('--markdown', action='store_true',
                        help='Export ZEEF Page to MD format. -p arg required')
    parser.add_argument('-v', '--version', help='displays the current version'
                        ' of pyzeef', action='store_true')
    return parser


def command_line():
    parser = get_parser()
    args = vars(parser.parse_args())
    token = None
    page = None

    if args['version']:
        print __version__
        return

    if args['token']:
        token = args['token']

    if args['p'] and not args['markdown']:
        d = Zeef(token)
        page = d.get_page(page_id=args['p'])
        # show page summary
        total_blocks = len(page.blocks)
        total_links = sum([len(i.links) for i in page.blocks])
        output = u"""{}: {}\n{}: {}\n{}: {}\n""".format(
            color_text('TITLE', 'yellow'), page.title,
            color_text('TOTAL BLOCKS', 'yellow'), total_blocks,
            color_text('TOTAL LINKS', 'yellow'), total_links
        )
        print output

    if args['pages']:
        if not token:
            return parser.print_help()
        d = Zeef(token, persist_pages=True)
        for page in d.pages:
            print u'- {} (ID: {})'.format(color_text(page.title, 'green'), page.id)

    if args['markdown']:
        if not token:
            return parser.print_help()

        page = args['p']
        if not page:
            return parser.print_help()
        d = Zeef(token)
        page = d.get_page(page_id=page)
        print page.to_markdown()

    if args['scratchpad']:
        d = Zeef(token, get_scratchpad=True)
        output = u"""Your Scratchpad\nLinks:\n"""
        if d.scratchpad.links:
            for link in d.scratchpad.links:
                output += u'{:<} - {}\n'.format(color_text(link['title'],
                                                           'yellow'),
                                                color_text(link['url'],
                                                           'green'))
        else:
            output = '\tNo Links\n'
        print output

if __name__ == '__main__':
    command_line()
