#!/usr/bin/python3

from urllib.request import urlopen as uo, urlretrieve as ur
from urllib.parse import urlencode as ue
from shutil import which
import subprocess
import argparse
import sys

try:
    from bs4 import BeautifulSoup as bs
except ModuleNotFoundError:
    print("BeautifulSoup4 not installed. Please install it."); sys.exit(1)

if not which("fzf"):
    print("fzf not installed. Please install it.")
    exit(1)

class scrape:
    baseurl = "https://man.archlinux.org"

    def __init__(self, keyword, download):
        self.dl = download

        query_string = {"q": keyword, "lang":"en"}
        self.url = self.baseurl + "/search?" +  ue(query_string)

    def __request(self):
        with uo(self.url) as req: self.response = req.read()

    def __bs4_parse(self):
        soup = bs(self.response, 'html.parser')
        ol = soup.find("section", class_="search-results").ol

        self.dict = {}
        for t in ol.select('a:nth-child(1)'): self.dict[t.text] = t['href']

    def __prompt(self):
        keys = '\n'.join(self.dict.keys())
        choice = subprocess.run('fzf', input=keys.encode(), stdout=subprocess.PIPE).stdout.decode()
        self.manlink = self.baseurl + self.dict[choice.replace('\n', '')] + '.raw'

    def __man_dl_or_view(self):
        if self.dl:
            ur(self.manlink, self.manlink.split('/')[-1])
            print("Manpage downloaded and saved to current file.")
        else:
            from tempfile import NamedTemporaryFile as temp
            with temp() as tmpfile:
                ur(self.manlink, tmpfile.name)
                subprocess.run(['man', '-l', tmpfile.name])

    def main_run(self):
        self.__request()
        self.__bs4_parse()
        self.__prompt()
        self.__man_dl_or_view()


def main():
    parser = argparse.ArgumentParser(description="View online manual pages (from https://man.archlinux.org) from the terminal.")
    parser.add_argument('-k', '--keyword', metavar='', type=str, help="keyword")
    parser.add_argument('-d', '--download', action="store_true", default=False)
    if len(sys.argv)==1 or '-k' not in sys.argv:
        print("Keyword not provided.\n")
        parser.print_help(sys.stderr)
        sys.exit(1)
    args = parser.parse_args()

    inst = scrape(args.keyword, args.download)
    inst.main_run()

if __name__ == "__main__":
    main()
