# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# 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.

"""Controllers for the library page."""

import json
import logging
import string

from constants import constants
from core.domain import acl_decorators
from core.controllers import base
from core.domain import collection_services
from core.domain import exp_services
from core.domain import summary_services
from core.domain import user_services
from core.platform import models
import feconf
import utils

(base_models, exp_models,) = models.Registry.import_models([
    models.NAMES.base_model, models.NAMES.exploration])
current_user_services = models.Registry.import_current_user_services()


def get_matching_activity_dicts(query_string, search_cursor):
    """Given a query string and a search cursor, returns a list of activity
    dicts that satisfy the search query.
    """
    # We only populate collections in the initial load, since the current
    # frontend search infrastructure is set up to only deal with one search
    # cursor at a time.
    # TODO(sll): Remove this special casing.
    collection_ids = []
    if not search_cursor:
        collection_ids, _ = (
            collection_services.get_collection_ids_matching_query(
                query_string))

    exp_ids, new_search_cursor = (
        exp_services.get_exploration_ids_matching_query(
            query_string, cursor=search_cursor))
    activity_list = []
    activity_list = (
        summary_services.get_displayable_collection_summary_dicts_matching_ids(
            collection_ids))
    activity_list += (
        summary_services.get_displayable_exp_summary_dicts_matching_ids(
            exp_ids))

    if len(activity_list) == feconf.DEFAULT_QUERY_LIMIT:
        logging.error(
            '%s activities were fetched to load the library page. '
            'You may be running up against the default query limits.'
            % feconf.DEFAULT_QUERY_LIMIT)
    return activity_list, new_search_cursor


class LibraryPage(base.BaseHandler):
    """The main library page. Used for both the default list of categories and
    for search results.
    """
    @acl_decorators.open_access
    def get(self):
        """Handles GET requests."""
        search_mode = 'search' in self.request.url

        if search_mode:
            page_mode = feconf.LIBRARY_PAGE_MODE_SEARCH
        else:
            page_mode = feconf.LIBRARY_PAGE_MODE_INDEX

        self.values.update({