# -*- coding: utf-8 -*-
import re
import urllib

import webapp2
from google.appengine.runtime import apiproxy_errors

from common import Jinja, Shortener
from pseudo_db import PseudoDB


class Album(webapp2.RequestHandler):
    shortened_list_regex = re.compile(r'^[a-z]{2}/[^&]+(&[a-z]{2}/[^&]+)*$')

    stylesheet_regex = re.compile(r'(?P<base>[^0-9]+)?(?P<number>[0-9]+)(?P<extension>\.css)?')
    # WARNING: remember to update if stylesheets are added or removed
    stylesheets = [
                   'anonymous1',
                   'anonymous2',
                   'anonymous3',
                  ]

    # WARNING: update if adding variables
    known_variables = [
                       'n', 't', 'name', 'title', 'ss', 'sheet', 'stylesheet', 'u', 'unmute',
                       'a', 'audio',
                      ]

    def get(self, ignore=None, url_list=None):
        '''Takes a list of semi-colon separated shortened lists of urls, expands them and displays all videos in a single page.'''
        shortened_lists = []
        if url_list:
            url_list = urllib.unquote(url_list)
            shortened_lists = PseudoDB.split_names_list(url_list)
        videos = []
        messages = []
        video_num = 0
        for shortened_list in shortened_lists:
            # each shortened_list corresponds to a list of mirrors for a
            # single video

            # strip superfluous slashes
            shortened_list = shortened_list.strip('/')
            # drop malformed entries
            if self.shortened_list_regex.match(shortened_list):
                expanded_urls = Shortener.expand_urls(shortened_list)
                if expanded_urls:
                    # add file type to urls that contain an extension
                    urls_list = []
                    for url in expanded_urls:
                        urls_list.append({'url': url, 'type': Shortener.get_mime_type(url)})
                    video_num += 1
                    video = {
                             'number' : video_num,
                             'urls' : urls_list,
                             'watch_url' : '/'+shortened_list,
                            }
                    videos.append(video)
            else:
                messages.append('Unrecognized url: {}'.format(shortened_list))

        # variables
        title = self.get_title()

        stylesheet, new_messages = self.get_stylesheet()
        if new_messages:
            messages += new_messages

        audio, new_messages = self.get_audio()
        if new_messages:
            messages += new_messages

        unmute, new_messages = self.get_unmute(videos)
        if new_messages:
            messages += new_messages

        new_messages = self.unknown_vars()
        if new_messages:
            messages += new_messages

        template_values = {
            'videos' : videos,
            'title' : title,
            'messages' : messages,
            'stylesheet' : stylesheet,
            'audio' : audio,
            'unmute' : unmute,
        }
        self.response.write(Jinja.render(self, 'album', template_values))

    def get_title(self):
        title = ''
        for variable in ['n', 't', 'name', 'title']:
            value = self.request.get(variable).encode('utf-8', 'ignore')
            if value:
                title = value
        return title

    def get_stylesheet(self):
        stylesheet = ''
        for variable in ['ss', 'sheet', 'stylesheet']:
            value = self.request.get(variable).encode('utf-8', 'ignore')
            if value:
                stylesheet = value
        if not stylesheet:
            return None, []

        match = Album.stylesheet_regex.match(stylesheet)
        if not match:
            return None, ['Unknown stylesheet: {}'.format(stylesheet)]

        # complete filename and drop extension
        if not match.group('base'):
            stylesheet = 'anonymous' + stylesheet
        # drop extension
        if match.group('extension'):
            stylesheet = stylesheet[:-4]

        # check that it exists
        if stylesheet in Album.stylesheets:
            return stylesheet, []
        return None, ['Unknown stylesheet: {}'.format(stylesheet)]

    def get_audio(self):
        messages = []
        audio = None
        for variable in ['a', 'audio']:
            value = self.request.get(variable).encode('utf-8', 'ignore')
            if value:
                audio = value
        if not audio:
            return None, messages

        expanded_audio = Shortener.expand_urls(audio, is_audio=True)
        audio_list = []
        if expanded_audio:
            for url in expanded_audio:
                audio_list.append({'url': url, 'type': Shortener.get_mime_type(url)})
        else:
            messages.append('Unknown url: {}'.format(audio))

        return audio_list, messages

    def get_unmute(self, videos):
        messages = []
        unmute = None
        for variable in ['u', 'unmute']:
            value = self.request.get(variable).encode('utf-8', 'ignore')
            if value:

                try:
                    value = int(value)
                except ValueError:
                    messages.append('Invalid video number; can\'t unmute: {}'.format(value))
                    value = None

            # can't just test value here since 0 will test false
            if isinstance(value, int):
                if 1 <= value <= len(videos):
                    unmute = value
                else:
                    messages.append('No such video; can\'t unmute: {}'.format(value))

        if not unmute:
            return None, messages
        return unmute, messages

    def unknown_vars(self):
        messages = []
        for variable in self.request.arguments():
            if not variable in self.known_variables:
                messages.append('Unknown variable: {}'.format(variable))
        return messages


application = webapp2.WSGIApplication([
    webapp2.Route('/a<ignore:(lbum)?>/<url_list:.*>', handler=Album),
    webapp2.Route('/a<ignore:(lbum)?>', handler=Album),
], debug=True)
