#!python
import json
from optparse import OptionParser, IndentedHelpFormatter
from americanas_scraper import search


class BannerHelpFormatter(IndentedHelpFormatter):
    "Just a small tweak to optparse to be able to print a banner."
    def __init__(self, banner, *argv, **argd):
        self.banner = banner
        IndentedHelpFormatter.__init__(self, *argv, **argd)

    def format_usage(self, usage):
        msg = IndentedHelpFormatter.format_usage(self, usage)
        return '%s\n%s' % (self.banner, msg)


# Parse the command line arguments.
formatter = BannerHelpFormatter(
    "Americanas crawler and scraper using beautifulsoup4\n"
    "By Geovany Rodrigues\n"
    "https://github.com/GeovRodri/americanas-scraper\n"
)

parser = OptionParser(formatter=formatter)
parser.add_option("--url", metavar="URL", type="string",
                  default="https://www.americanas.com.br/categoria/celulares-e-smartphones/smartphone/",
                  help="URL")

(options, args) = parser.parse_args()
params = [(k, v) for (k, v) in options.__dict__.items() if not k.startswith('_')]
params = dict(params)

# Run the query.
for item in search(**params):
    print(item)
