

import os
import sys
import urllib2
from bs4 import BeautifulSoup

from flask import Flask
app = Flask(__name__)
app.config['DEBUG'] = True

# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.


class Episode:
    def __init__(self, season, episode, link):
        self.season = season
        self.episode = episode
        self.link = link

    def __str__(self):
        return ''.join([str(self.season), ' ', str(self.episode)])


def get_web_page(url, user_agent="Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", verbose=True):
    page = None

    try:
        headers = {'User-Agent': user_agent}

        if verbose:
            print 'Requesting :', url

        req = urllib2.Request(url, None, headers)
        response = urllib2.urlopen(req)

        if verbose:
            print 'loading page'
        page = response.read()

        response.close()
    except:
        page = None

    return page


def get_show_list(url='http://streamallthis.is/tv-shows-list.html', verbose=True):
    list = None

    page = get_web_page(url, verbose=verbose)

    if page:
        soup = BeautifulSoup(page)
        list = soup.body.findAll('a', attrs={'class': 'lc'})
        list = dict([ (l.string, l.attrs['href']) for l in list ])

    return list


def get_show_link(show_list, show_name, url, verbose=True):
    show_url = None

    if not show_list or len(show_list) == 0:
        raise ValueError

    shows = filter(lambda x: show_name.upper() in x, show_list)
    if shows:
        show_url = [''.join([url, show_list[show], '/']) for show in shows]
    else:
        print 'Query yield no result'

    return show_url


def get_show_episode_list(show_url, base_url, verbose=True):
    if not show_url or not base_url:
        raise ValueError

    episodes = None

    page = get_web_page(show_url, verbose=verbose)
    if page:
        episodes = []
        soup = BeautifulSoup(page)
        for episode in soup.body.findAll('tr', attrs={'class': 'fc'}):
            content = episode.findAll('td')
            href = content[3].findAll('a', attrs={'class': 'la'})
            if href and len(href) > 0:
                href = href[0].attrs['href']
                href = ''.join([base_url, href])
                episodes.append(Episode(int(content[1].text), int(content[2].text), href))
    else:
        print 'Unable to get the page show list'

    return episodes


def get_episode_video(episodes, season, ep, base_url):
    url = None

    if not episodes or len(episodes) == 0 or not base_url:
        raise ValueError

    episode = filter(lambda x: x.season == season and x.episode == ep, episodes)
    episode = episode[0] if len(episode) == 1 else None

    if episode:
        episode_video_page = get_web_page(episode.link)
        soup = BeautifulSoup(episode_video_page)
        iframe = filter(lambda x: 'ads' not in x.attrs['src'], soup.body.findAll('iframe'))
        if len(iframe) > 0:
            url = ''.join([base_url, iframe[0].attrs['src']])
            video_page = get_web_page(url)
            soup = BeautifulSoup(video_page)
            try:
                video_link_tag = soup.body.findAll("div", attrs={"class":"badsvideo"})[0]
                url = ''.join([base_url, video_link_tag.attrs["onclick"].replace("window.location.href='",'')])
                url = url.replace("'",'')
            except:
                pass
        else:
            print "can't find video iframe"
    else:
        print "can't find any episode for the requested season: ", season, "episode: ", ep

    return url

show_list = get_show_list()
url='http://streamallthis.is/'

@app.route('/')
def hello():
    """Return a friendly HTTP greeting."""
    return 'Hello World!'


@app.route('/list')
def list():
    """Return the list of the available shows"""
    show_list_str = '<p>'

    if show_list is None or len(show_list) == 0:
        return page_not_found(ValueError)

    i = 0
    for key in show_list:
        show_list_str += ''.join(['<a href=/show/',str(i),'>', str(i), key, '</a>', '<br>'])
        i += 1
    show_list_str += '</p>'

    return show_list_str

@app.route('/show/<int:showId>')
def show(showId):
    page = page_not_found(ValueError)

    try:
        show_info = show_list.items()[showId]
        show_name = show_info[0]
        show_url = show_info[1]

        link = get_show_link(show_list, show_name, 'http://streamallthis.is')
        episodes = get_show_episode_list(link[0], 'http://streamallthis.is')

        if episodes:
            page = ''.join(['<p>', show_name, '<br>'])
            for i in episodes:
                season = i.season
                episode = i.episode
                video_episode_link = get_episode_video(episodes, season, episode, 'http://streamallthis.is')
                page += ''.join(['<a href=', video_episode_link, '>', 'season : ', str(season), ' episode : ', str(episode), '</a>', '<br>'])
            page += '</p>'
    except:
        pass

    return page


@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, nothing at this URL.', 404
