#!/usr/bin/env python3

import getopt
import sys
from pyquery import PyQuery as pq


def get_data(file=None):
    if not file:
        data = sys.stdin.read()
    else:
        with open(file) as f:
            data = f.read()
    return data


def query(file, select, attr, text):
    data = get_data(file)
    d = pq(data)
    if select:
        if attr:
            return(d(select).attr(attr))
        elif text:
            return(d(select).text())
        else:
            return(d(select))


def print_data(data, output):
    print(data)


def usage():
    print('Usage:')
    print('-h, --help      ')
    print('-o, --output    ')
    print('-v, --version   ')
    print('-s, --select    \'query_str\'')
    print('-a, --attr      \'attr_name\'')
    print('-t, --text      ')
    print('-H, --html      ')
    print('-f, --file      <file>')
    print();
    print("'-H' prints the html of the founded search");
    print("'-t' prints thr inner text of the founded search");
    print("if no file is given it reads from `stdin`.");
    print();
    print("examples:");
    print("pyquery-cli -s'#myid'");
    print("pyquery-cli -s'.myclass' -a'name'");
    print();


def print_version():
    print('v0.0.1')


def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:vtHs:a:f:", ["help", "output=", "select=", "attr=", "file=", "text", "html"])
    except getopt.GetoptError as err:
        print(err)
        sys.exit(2)
    output = None
    file = None
    attr = None
    select = None
    text = None
    for o, a in opts:
        if o in ("-v", "version"):
            print_version()
            sys.exit()
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        elif o in ("-s", "--select"):
            select = a
        elif o in ("-a", "--attr"):
            attr = a
        elif o in ("-f", "--file"):
            file = a
        elif o in ("-t", "--text"):
            text = True
        elif o in ("-H", "--html"):
            None
        else:
            assert False, "unhandled option"
    print_data(query(file, select, attr, text),output)

if __name__ == "__main__":
    main()
