#!/usr/bin/env python

# Copyright 2011 Josh Kearney
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""wootoff - Monitor a wootoff."""

import optparse
import subprocess
import sys
import time
import urllib

from BeautifulSoup import BeautifulSoup


__VERSION__ = "wootoff v0.0.1 - https://github.com/jk0/wootoff"


def build_options():
    """Generate command line options."""
    parser = optparse.OptionParser(version=__VERSION__)

    parser.add_option("--keyword", help="watch for a specific keyword")
    parser.add_option("--refresh_interval", default=30, type="int",
            help="refresh interval of the woot fetcher")
    parser.add_option("--verbose", action="store_true",
            help="show verbose output")

    return parser.parse_args()


def fetch_url(url):
    """Fetch and return the object of then given URL."""
    class WootOffURLopener(urllib.FancyURLopener):
        version = __VERSION__

    urllib._urlopener = WootOffURLopener()

    try:
        return urllib.urlopen(url)
    except IOError:
        return None


def get_wootoff_item():
    """Get and return the current wootoff item."""
    response = fetch_url("http://www.woot.com")
    soup = BeautifulSoup(response.read())
    item_desc = soup.find("h2", {"class": "fn"})
    item_url = soup.find("a", {"id": ("ContentPlaceHolderLeadIn_ContentPlaceHo"
            "lderLeadIn_SaleControl_HyperLinkWantOne")})

    return (item_desc.contents[0], item_url["href"])


def main():
    """Main loop."""
    options, args = build_options()

    verbose = options.verbose or False
    keyword = options.keyword
    refresh_int = options.refresh_interval

    if keyword:
        keyword = keyword.upper()

    try:
        while True:
            item_desc, item_url = get_wootoff_item()

            if keyword in [word.upper() for word in item_desc.split(" ")]:
                alert = "say keyword '%s' found, loading in browser" % keyword
                subprocess.call(alert.split(" "))
                subprocess.call(["open", item_url])
                sys.exit(0)

            if verbose:
                print "%s => %s" % (item_desc, item_url)

            time.sleep(refresh_int)
    except KeyboardInterrupt:
        sys.exit(0)


if __name__ == "__main__":
    main()
