class SuggestionCreator(object):
    @classmethod
    def createTeamMediaSuggestion(cls,
                                  author_account_key,
                                  media_url,
                                  team_key,
                                  year_str,
                                  private_details_json=None,
                                  is_social=False,
                                  default_preferred=False):
        """Create a Team Media Suggestion. Returns status (success, suggestion_exists, media_exists, bad_url)"""

        media_dict = MediaParser.partial_media_dict_from_url(media_url)
        if media_dict is not None:
            if media_dict.get("is_social", False) != is_social:
                return 'bad_url', None

            existing_media = Media.get_by_id(
                Media.render_key_name(media_dict['media_type_enum'],
                                      media_dict['foreign_key']))
            if existing_media is None or team_key not in [
                    reference.id() for reference in existing_media.references
            ]:
                foreign_type = Media.SLUG_NAMES[media_dict['media_type_enum']]
                suggestion_id = Suggestion.render_media_key_name(
                    year_str, 'team', team_key, foreign_type,
                    media_dict['foreign_key'])
                suggestion = Suggestion.get_by_id(suggestion_id)
                if not suggestion or suggestion.review_state != Suggestion.REVIEW_PENDING:
                    media_dict['year'] = int(year_str) if year_str else None
                    media_dict['reference_type'] = 'team'
                    media_dict['reference_key'] = team_key
                    media_dict['default_preferred'] = default_preferred
                    if private_details_json is not None:
                        media_dict[
                            'private_details_json'] = private_details_json

                    target_model = "media"
                    if media_dict.get("is_social", False):
                        target_model = "social-media"

                    if media_dict.get('media_type',
                                      '') in MediaType.robot_types:
                        target_model = "robot"

                    if Event.validate_key_name(team_key):
                        target_model = 'event_media'
                        media_dict['reference_type'] = 'event'

                    suggestion = Suggestion(
                        id=suggestion_id,
                        author=author_account_key,
                        target_model=target_model,
                    )
                    suggestion.contents = media_dict
                    suggestion.put()
                    return 'success', suggestion
                else:
                    return 'suggestion_exists', None
            else:
                return 'media_exists', None
        else:
            return 'bad_url', None

    @classmethod
    def createEventMediaSuggestion(cls,
                                   author_account_key,
                                   media_url,
                                   event_key,
                                   private_details_json=None):
        """Create an Event Media Suggestion. Returns status (success, suggestion_exists, media_exists, bad_url)"""

        media_dict = MediaParser.partial_media_dict_from_url(media_url)
        if media_dict is not None:
            if media_dict[
                    'media_type_enum'] != MediaType.YOUTUBE_VIDEO and media_dict[
                        'media_type_enum'] != MediaType.INTERNET_ARCHIVE_VIDEO:
                return 'bad_url', None

            existing_media = Media.get_by_id(
                Media.render_key_name(media_dict['media_type_enum'],
                                      media_dict['foreign_key']))
            if existing_media is None or event_key not in [
                    reference.id() for reference in existing_media.references
            ]:
                foreign_type = Media.SLUG_NAMES[media_dict['media_type_enum']]
                suggestion_id = Suggestion.render_media_key_name(
                    event_key[:4], 'event', event_key, foreign_type,
                    media_dict['foreign_key'])
                suggestion = Suggestion.get_by_id(suggestion_id)
                if not suggestion or suggestion.review_state != Suggestion.REVIEW_PENDING:
                    media_dict['year'] = event_key[:4]
                    media_dict['reference_type'] = 'event'
                    media_dict['reference_key'] = event_key
                    target_model = 'event_media'
                    if private_details_json is not None:
                        media_dict[
                            'private_details_json'] = private_details_json

                    suggestion = Suggestion(
                        id=suggestion_id,
                        author=author_account_key,
                        target_model=target_model,
                    )
                    suggestion.contents = media_dict
                    suggestion.put()
                    return 'success', suggestion
                else:
                    return 'suggestion_exists', None
            else:
                return 'media_exists', None
        else:
            return 'bad_url', None

    @classmethod
    def createEventWebcastSuggestion(cls, author_account_key, webcast_url,
                                     webcast_date, event_key):
        """Create a Event Webcast Suggestion. Returns status string"""

        webcast_url = WebsiteHelper.format_url(webcast_url)

        webcast_date = webcast_date.strip()
        if webcast_date:
            try:
                datetime.strptime(webcast_date, "%Y-%m-%d")
            except ValueError:
                return 'invalid_date'
        else:
            webcast_date = None

        try:
            webcast_dict = WebcastParser.webcast_dict_from_url(webcast_url)
        except Exception, e:
            logging.exception(e)
            webcast_dict = None

        if webcast_dict is not None:
            # Check if webcast already exists in event
            event = Event.get_by_id(event_key)
            if not event:
                return 'bad_event'
            if event.webcast and webcast_dict in event.webcast:
                return 'webcast_exists'
            else:
                suggestion_id = Suggestion.render_webcast_key_name(
                    event_key, webcast_dict)
                suggestion = Suggestion.get_by_id(suggestion_id)
                # Check if suggestion exists
                if not suggestion or suggestion.review_state != Suggestion.REVIEW_PENDING:
                    suggestion = Suggestion(
                        id=suggestion_id,
                        author=author_account_key,
                        target_model="event",
                        target_key=event_key,
                    )
                    suggestion.contents = {
                        "webcast_dict": webcast_dict,
                        "webcast_url": webcast_url,
                        "webcast_date": webcast_date
                    }
                    suggestion.put()
                    return 'success'
                else:
                    return 'suggestion_exists'
        else:  # Can't parse URL -- could be an obscure webcast. Save URL and let a human deal with it.
            contents = {
                "webcast_url": webcast_url,
                "webcast_date": webcast_date
            }

            # Check if suggestion exists
            existing_suggestions = Suggestion.query(
                Suggestion.target_model == 'event',
                Suggestion.target_key == event_key).fetch()
            for existing_suggestion in existing_suggestions:
                if existing_suggestion.contents == contents:
                    return 'suggestion_exists'

            suggestion = Suggestion(
                author=author_account_key,
                target_model="event",
                target_key=event_key,
            )
            suggestion.contents = contents
            suggestion.put()
            return 'success'
class SuggestionCreator(object):
    @classmethod
    def createTeamMediaSuggestion(cls,
                                  author_account_key,
                                  media_url,
                                  team_key,
                                  year_str,
                                  private_details_json=None,
                                  is_social=False):
        """Create a Team Media Suggestion. Returns status (success, suggestion_exists, media_exists, bad_url)"""

        media_dict = MediaParser.partial_media_dict_from_url(media_url)
        if media_dict is not None:
            if media_dict.get("is_social", False) != is_social:
                return 'bad_url', None

            existing_media = Media.get_by_id(
                Media.render_key_name(media_dict['media_type_enum'],
                                      media_dict['foreign_key']))
            if existing_media is None or team_key not in [
                    reference.id() for reference in existing_media.references
            ]:
                foreign_type = Media.SLUG_NAMES[media_dict['media_type_enum']]
                suggestion_id = Suggestion.render_media_key_name(
                    year_str, 'team', team_key, foreign_type,
                    media_dict['foreign_key'])
                suggestion = Suggestion.get_by_id(suggestion_id)
                if not suggestion or suggestion.review_state != Suggestion.REVIEW_PENDING:
                    media_dict['year'] = int(year_str) if year_str else None
                    media_dict['reference_type'] = 'team'
                    media_dict['reference_key'] = team_key
                    if private_details_json is not None:
                        media_dict[
                            'private_details_json'] = private_details_json

                    target_model = "media"
                    if media_dict.get("is_social", False):
                        target_model = "social-media"

                    if media_dict.get('media_type',
                                      '') in MediaType.robot_types:
                        target_model = "robot"

                    suggestion = Suggestion(
                        id=suggestion_id,
                        author=author_account_key,
                        target_model=target_model,
                    )
                    suggestion.contents = media_dict
                    suggestion.put()
                    return 'success', suggestion
                else:
                    return 'suggestion_exists', None
            else:
                return 'media_exists', None
        else:
            return 'bad_url', None

    @classmethod
    def createEventWebcastSuggestion(cls, author_account_key, webcast_url,
                                     event_key):
        """Create a Event Webcast Suggestion. Returns status string"""

        webcast_url = webcast_url.strip()
        if not webcast_url.startswith(
                'http://') and not webcast_url.startswith('https://'):
            webcast_url = 'http://' + webcast_url

        try:
            webcast_dict = WebcastParser.webcast_dict_from_url(webcast_url)
        except Exception, e:
            logging.exception(e)
            webcast_dict = None

        if webcast_dict is not None:
            # Check if webcast already exists in event
            event = Event.get_by_id(event_key)
            if not event:
                return 'bad_event'
            if event.webcast and webcast_dict in event.webcast:
                return 'webcast_exists'
            else:
                suggestion_id = Suggestion.render_webcast_key_name(
                    event_key, webcast_dict)
                suggestion = Suggestion.get_by_id(suggestion_id)
                # Check if suggestion exists
                if not suggestion or suggestion.review_state != Suggestion.REVIEW_PENDING:
                    suggestion = Suggestion(
                        id=suggestion_id,
                        author=author_account_key,
                        target_model="event",
                        target_key=event_key,
                    )
                    suggestion.contents = {
                        "webcast_dict": webcast_dict,
                        "webcast_url": webcast_url
                    }
                    suggestion.put()
                    return 'success'
                else:
                    return 'suggestion_exists'
        else:  # Can't parse URL -- could be an obscure webcast. Save URL and let a human deal with it.
            contents = {"webcast_url": webcast_url}

            # Check if suggestion exists
            existing_suggestions = Suggestion.query(
                Suggestion.target_model == 'event',
                Suggestion.target_key == event_key).fetch()
            for existing_suggestion in existing_suggestions:
                if existing_suggestion.contents == contents:
                    return 'suggestion_exists'

            suggestion = Suggestion(
                author=author_account_key,
                target_model="event",
                target_key=event_key,
            )
            suggestion.contents = contents
            suggestion.put()
            return 'success'