# Copyright 2014 Google Inc. 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.

"""Module providing visualizations display as HTML/JS."""

__author__ = 'Mike Gainer (mgainer@google.com)'

from common import safe_dom
from controllers import utils
from models import data_sources
from models import jobs
from models import transforms
from models.analytics import utils as analytics_utils
from modules.mapreduce import mapreduce_module


def _generate_display_html(template_renderer, xsrf, app_context,
                           visualizations):
    # Package-protected: pylint: disable=protected-access

    # First, load jobs for all generators required for an visualization.
    # Jobs may directly contain small results, just hold references to
    # larger results, or both.
    any_generator_not_running = False
    data_source_jobs = {}
    for generator_class in analytics_utils._generators_for_visualizations(
        visualizations):
        job = generator_class(app_context).load()
        data_source_jobs[generator_class] = job
        if not job or job.has_finished:
            any_generator_not_running = True

    # Generate HTML section for each visualization.
    html_sections = []
    for v in visualizations:
        html_sections.extend(_generate_visualization_section(
            template_renderer, xsrf, app_context, v, data_source_jobs))

    # Generate JS to pull contents of data-sources up to page and feed it
    # to visualization functions.
    html_sections.extend(_generate_data_source_script(template_renderer,
                                                      visualizations, xsrf))

    # Generate page content
    names_of_visualizations_with_generators = []
    for visualization in visualizations:
        if analytics_utils._generators_for_visualizations([visualization]):
            names_of_visualizations_with_generators.append(visualization.name)
    rest_sources = [{
        'name': rdsc.get_name(),
        'title': rdsc.get_title(),
        'chunk_size': rdsc.get_default_chunk_size(),
        } for rdsc in analytics_utils._rest_data_source_classes(visualizations)]
    return template_renderer.render(
        None, 'models/analytics/display.html',
        {
            'sections': html_sections,
            'any_generator_not_running': any_generator_not_running,
            'xsrf_token_run': xsrf.create_xsrf_token('run_visualizations'),
            'visualizations': names_of_visualizations_with_generators,
            'rest_sources': rest_sources,
            'r': template_renderer.get_current_url(),
        })


def _generate_visualization_section(template_renderer, xsrf, app_context,