# -*- coding: utf-8 -*-
# Moovida - Home multimedia server
# Copyright (C) 2006-2009 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Moovida with Fluendo's plugins.
#
# The GPL part of Moovida is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Moovida" in the root directory of this distribution package
# for details on that license.

"""
Benchmark Utility
"""

__maintainer__ = 'Benjamin Kampmann <benjamin@fluendo.com>'

import pkg_resources, sys
try:
    import gtk
except ImportError:
    gtk = None

LOGO_PATH = pkg_resources.resource_filename('elisa.core', 'data/splash.png')

def print_report(data):
    level, msg = create_critical(data)
    print create_report(data)
    if level:
        print msg
        if level==5:
            sys.exit(0)

def create_report(data):
    report = 'Hardware accelartion\t: %s\n' % data.hardware_acceleration
    report += 'Shaders for videos\t\t: %s\n' % data.shaders
    report += 'Frames per second analysis: (%dx%d)\n' % data.size
    report += '\tmax:\t\t\t%s\n' % data.max_rate
    report += '\tmin:\t\t\t\t%s\n' % data.min_rate
    report += '\taverage:\t\t\t%s\n' % data.average
    report += '\tlower_median:\t\t%s\n' % data.lower_median
    report += '\tmedian:\t\t\t%s\n' % data.median
    report += '\tupper_median:\t%s\n' % data.upper_median
    report += '\t\t\t\t\t\tof %s FPS\n' % len(data.frame_rates)
    return report

def create_critical(data):
    if data.hardware_acceleration == False:
        # NO GO!
        return (5, "Hardware acceleration is missing")

    level = 0
    msg = ""
    if not data.shaders:
        level = 3
        msg +="Video shaders missing. Moovida is probably running, but" \
               " might be slow when playing videos.\n"

    """
    if data.average < 60:
        level = 5
        msg += "Sorry, the frame rate of your graphic card is to slow" \
                " to run Moovida properly."
    elif data.average < 100:
        level = 3
        msg += "Your frame rate of your graphic card is a bit slow," \
                " Moovida may shows some cliches."
    """
    if level == 0:
        msg = "Everything is fine!"

    return (level, msg)

def run_benchmark(callback):
    
    try:
        import pgm
    except ImportError:
        print "Pigment not found. Doing Benchmark failed!"
        sys.exit(0)

    try:
        from pgm.utils.benchmark import Benchmark
    except ImportError:
        print "Could not import Benchmark. Maybe your pigment is too old?"
        return callback()

    b = Benchmark()

    def got_result(data):
        if gtk:
            window = show_gtkreport(report=data, callback=callback)
        else:
            print_report(data)
            if callback:
                callback()

    b.callback = got_result
    b.picture_path = LOGO_PATH
    b.frames = 100
    b.start()

class ReportViewer:

        def __init__(self, report=None, msg=None, callback=None):
            self._callback = callback
            self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
            self.window.set_position(gtk.WIN_POS_CENTER_ALWAYS)
            self.window.connect("delete_event", self.delete_event)    
            self.window.set_border_width(10)
            self.window.set_title("Moovida Media Center")
            self.vbox = gtk.VBox(False, 2)
            self.window.add(self.vbox)

            self.info_box = gtk.HBox(False, 2)
            self.vbox.add(self.info_box)

            # error icon
            self.icon = gtk.Image()
            self.info_box.add(self.icon)

            # error message
            self.label = gtk.Label()
            self.info_box.add(self.label)

            # buttons
            self.button_box = gtk.HBox(False, 1)
            self.vbox.add(self.button_box)
            self.button_box.show()


            if report:
                if report.hardware_acceleration == False:
                    msg = "Your graphical hardware is not properly configured to\n"\
                          "support 3D software such as Moovida Media Center."
                    self.icon.set_from_stock(gtk.STOCK_DIALOG_ERROR,
                                             gtk.ICON_SIZE_DIALOG)
                    # quit button
                    self.quit = gtk.Button("Quit", stock=gtk.STOCK_QUIT)
                    self.quit.connect('clicked', self.btn_quit)
                    self.button_box.pack_end(self.quit, expand=False)
                    self.quit.show()

                elif not report.shaders:
                    msg = "Your are using legacy graphical hardware. Moovida Media Center\n"\
                          "might run fine but video playback will be slow."
                    self.icon.set_from_stock(gtk.STOCK_DIALOG_INFO,
                                             gtk.ICON_SIZE_DIALOG)
                    self.button = gtk.Button('Start Moovida', stock=gtk.STOCK_OK)
                    self.button.connect('clicked', self.btn_clicked)
                    self.button.connect_object("clicked", gtk.Widget.destroy, self.window)
                    self.button_box.pack_end(self.button, expand=False)
                    self.button.show()
                else:
                    if callback:
                        callback()
                        return
            else:
                self.icon.set_from_stock(gtk.STOCK_DIALOG_ERROR,
                                         gtk.ICON_SIZE_DIALOG)
                # quit button
                self.quit = gtk.Button("Quit", stock=gtk.STOCK_QUIT)
                self.quit.connect('clicked', self.btn_quit)
                self.button_box.pack_end(self.quit, expand=False)
                self.quit.show()

            self.label.set_label(msg)

            self.vbox.show()
            self.info_box.show()
            self.icon.show()
            self.label.show()
            self.window.show()

        def delete_event(self, widget, event, data=None):
            if self._callback:
                self._callback()
            return False

        def btn_clicked(self, bla):
            if self._callback:
                self._callback()
            return False

        def btn_quit(self, bla):
            sys.exit(1)
        
def show_gtkreport(report, callback = None):
    return ReportViewer(report, callback=callback)
