import json
import logging
import re
from urllib import urlencode
from urlparse import urlparse

from google.appengine.api import urlfetch

from BeautifulSoup import BeautifulSoup
from consts.media_type import MediaType


class MediaHelper(object):
    SOCIAL_SORT_ORDER = {
        MediaType.FACEBOOK_PROFILE: 0,
        MediaType.YOUTUBE_CHANNEL: 1,
        MediaType.TWITTER_PROFILE: 2,
        MediaType.INSTAGRAM_PROFILE: 3,
        MediaType.PERISCOPE_PROFILE: 4,
        MediaType.GITHUB_PROFILE: 5,
    }

    @classmethod
    def group_by_slugname(cls, medias):
        medias_by_slugname = {}
        for media in medias:
            slugname = media.slug_name
            if slugname in medias_by_slugname:
                medias_by_slugname[slugname].append(media)
            else:
                medias_by_slugname[slugname] = [media]
        return medias_by_slugname

    @classmethod
    def get_images(cls, medias):
        return filter(lambda m: m.media_type_enum in MediaType.image_types, medias)

    @classmethod
    def get_socials(cls, medias):
        return filter(lambda m: m.media_type_enum in MediaType.social_types, medias)

    @classmethod
    def social_media_sorter(cls, media):
        return cls.SOCIAL_SORT_ORDER.get(media.media_type_enum, 1000)


class MediaParser(object):

    # Add MediaTypes to this list to indicate that they case case-sensitive (shouldn't be normalized to lower case)
    CASE_SENSITIVE_FOREIGN_KEYS = [MediaType.YOUTUBE_VIDEO, MediaType.IMGUR, MediaType.CD_PHOTO_THREAD]

    # Dict that maps media types -> list of tuple of regex pattern and group # of foreign key
    FOREIGN_KEY_PATTERNS = {
        MediaType.FACEBOOK_PROFILE: [(r".*facebook.com\/(.*)(\/(.*))?", 1)],
        MediaType.TWITTER_PROFILE: [(r".*twitter.com\/(.*)(\/(.*))?", 1)],
        MediaType.YOUTUBE_CHANNEL: [(r".*youtube.com\/user\/(.*)(\/(.*))?", 1),
                                    (r".*youtube.com\/c\/(.*)(\/(.*))?", 1),
                                    (r".*youtube.com\/(.*)(\/(.*))?", 1)],
        MediaType.GITHUB_PROFILE: [(r".*github.com\/(.*)(\/(.*))?", 1)],
        MediaType.YOUTUBE_VIDEO: [(r".*youtu\.be\/(.*)", 1), (r".*v=([a-zA-Z0-9_-]*)", 1)],
        MediaType.IMGUR: [(r".*imgur.com\/(\w+)\/?\Z", 1), (r".*imgur.com\/(\w+)\.\w+\Z", 1)],
        MediaType.INSTAGRAM_PROFILE: [(r".*instagram.com\/(.*)(\/(.*))?", 1)],
        MediaType.PERISCOPE_PROFILE: [(r".*periscope.tv\/(.*)(\/(.*))?", 1)],
        MediaType.GRABCAD: [(r".*grabcad.com\/library\/(.*)", 1)]
    }

    # Media URL patterns that map a URL -> Profile type (used to determine which type represents a given url)
    # This is a list because the order matters
    URL_PATTERNS = [