#!/usr/bin/python
# Copyright 2014 Google.
#
# 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.
#
# A HTML-generating codec comparison tool.
#
import visual_metrics

import argparse
import sys

import gviz_api
import pick_codec
import score_tools

def FormatAsHtml(codecs, datatable, metric_name):
  """
  Print out the data recorded in "data" in an HTML file.
  data first level: codec
  second level: filename
  third level: bitrate/psnr pairs.
  """

  snrs = ''
  filestable = {}
  filestable['dsnr'] = ''
  filestable['drate'] = ''
  filestable['avg'] = ''


  # Other_Codecs is directories after the baseline to compare to the base.
  other_codecs = codecs[1:]
  baseline_codec = codecs[0]

  page_title = '%s compared to %s' % (pick_codec.LongName(baseline_codec),
      ' and '.join([pick_codec.LongName(codec) for codec in other_codecs]))

  page_subtitle = 'Best encodings based on the &quot;%s&quot; criterion' % (
    metric_name)

  for metric in ['avg', 'dsnr', 'drate']:
    gviz_data_table = visual_metrics.BuildGvizDataTable(
      datatable, metric, baseline_codec, other_codecs)

    filestable[metric] = ( filestable[metric] + "filestable_" + metric +
                           "[1]=" + gviz_data_table.ToJSon()
                           + "\n" )

  # Now we collect all the data for all the graphs.  First the column
  # headers which will be Datarate and then each this_codec.
  # columns = ("datarate", baseline_codec)
  description = {"datarate":("number", "Datarate")}
  for this_codec in other_codecs:
    description[this_codec] = ("number", this_codec)

  description[baseline_codec] = ("number", baseline_codec)

  snrs = snrs + "snrs[1] = ["

  # Now collect the data for the graphs, file by file.
  snr_data = []
  # Find the metric files in the baseline codec.
  videofile_name_list = datatable[baseline_codec].keys()

  for filename in videofile_name_list:

    data = []

    # Collect the file in each codec and store all of its metrics
    # in the associated gviz metrics table.
    for this_codec in codecs:

      if not this_codec in datatable or not filename in datatable[this_codec]:
        continue

      # Read and parse the metrics file storing it to the data we'll
      # use for the gviz_api.Datatable.
      metrics = datatable[this_codec][filename]
      for bitrate, metric in metrics:
        data.append({"datarate": bitrate, this_codec: metric})

    data_table = gviz_api.DataTable(description)
    data_table.LoadData(data)
    snr_data.append(data_table.ToJSon(
      columns_order=tuple(["datarate",baseline_codec]+other_codecs)))

  snrs = "snrs[1] = ['%s',]\n" % "','".join(snr_data)

  formatters = ""
  for i in range(len(other_codecs)):
    formatters = "%s   formatter.format(better, %d);" % (formatters, i+1)

  # The template file is the html file into which we will write the
  # data from the stats file, formatted correctly for the gviz_api.
  template_file = open('lib/metrics_template.html', "r")
  page_template = template_file.read()
  template_file.close()

  print visual_metrics.HtmlPage(page_template, page_title=page_title,
                                page_subtitle=page_subtitle,
                                filestable=filestable, snrs=snrs,
                                formatters=formatters)
  return


def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--score', action='store_true', default=False)
  parser.add_argument('--criterion', default='psnr')
  parser.add_argument('codecs', nargs='*')
  args = parser.parse_args()

  datatable = {}
  score_function = score_tools.PickScorer(args.criterion)
  visual_metrics.ListMpegResults(args.codecs, args.score, datatable,
                                 score_function=score_function)
  FormatAsHtml(args.codecs, datatable, args.criterion)
  return 0

if __name__ == '__main__':
  sys.exit(main())
