# -*- coding: utf-8 -*-
# Elisa - Home multimedia server
# Copyright (C) 2006-2008 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 Elisa with Fluendo's plugins.
#
# The GPL part of Elisa is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Elisa" in the root directory of this distribution package
# for details on that license.


__maintainer__ = 'Lionel Martin <lionel@fluendo.com>'
__maintainer2__ = 'Florian Boucault <florian@fluendo.com>'


from elisa.base_components.view import View
from twisted.internet import reactor
from report_tools import ReportTools

import pygtk
pygtk.require('2.0')
import gtk

import gc
import inspect

class HelperStartupView(View):
    """
    This class implements gtk list view support
    """

    supported_controllers = ('raval:elisa_controller',)

    def __init__(self):
        View.__init__(self)
        self.context_path = 'helper:glade_context'
        self.menu = None
        self.player = None
        self._refresh_rate = 1.0
        self.report_tools = ReportTools()
        self.object_tree_view = None
        self._auto_refresh = False
        self._use_snapshots = False
        self._use_startup_snapshot = True
        self._startup_snapshot = None
        self._current_snapshot = None
        
        """
        self.box = gtk.VBox()
        self.context_handle = self.box
        """

    def controller_changed(self, old_controller, new_controller):
        self.context_handle = self.frontend.context.glade_tree.get_widget("MainBox")
        glade_tree = self.frontend.context.glade_tree
        
        dic = { 
               "on_InfoRefreshRate1_value_changed" : self.change_info_refresh_rate,
               "on_InfoAutoRefresh1_toggled"       : self.toggle_info_refresh,
               "on_InfoRefreshbutton1_clicked"     : self.refresh_clicked,
               "on_InfoUseSnapshot1_toggled"       : self.toggle_use_snapshots,
               "on_InfoSnapshotButton1_clicked"    : self.take_snapshot_clicked,
               "on_InfoSnapshotCombo1_changed"     : self.combo_Snapshot_changed,
               "on_ObjectTreeView1_row_expanded"   : self.row_expanded,
               }
        glade_tree.signal_autoconnect(dic)
        InfoSnapshotCombo = self.frontend.context.glade_tree.get_widget("InfoSnapshotCombo1")
        InfoSnapshotCombo.set_active(0)
        self._use_startup_snapshot = True
        
        self.instance_tree_view = glade_tree.get_widget("ObjectTreeView1")
        self.create_table_columns(self.instance_tree_view,
                                  ['class name', 'count or instance id'], 1)
        treestore = gtk.TreeStore(str, int, object)
        self.instance_tree_view.set_model(treestore)
        treestore.set_sort_column_id(1, gtk.SORT_DESCENDING)
        self._startup_snapshot = self.report_tools.get_instance_infos()
        self._current_snapshot =self._startup_snapshot
        
        self.refresh()
        
        
    def refresh_clicked(self, bt):
        self.refresh()
        
        
    def refresh(self):
        #Refresh the instance infos
        self.debug("Refresh the instance infos")
        if self._use_snapshots == True:
            if self._use_startup_snapshot == True:
                snapshot = self._startup_snapshot
            else:
                snapshot = self._current_snapshot
        else:
            snapshot = None
            
        current_instances = self.report_tools.get_instance_infos(snapshot)
        self.refresh_table(self.instance_tree_view, current_instances)
        if self._auto_refresh:
            reactor.callLater(self._refresh_rate, self.refresh)
        
    
    def refresh_table(self, treeview, data):
        treestore = treeview.get_model()
        if treestore != None:
            treestore.clear()
            for key, value in data.iteritems():
                line = [key, value[0], value[1]]
                parent = treestore.append(None, line)
                treestore.append(parent, ["Loading", 0, None])

    def create_table_columns(self, treeview, columns, ordered_column=0):
        i=0
        for name in columns:
            tvcolumn = gtk.TreeViewColumn(name)
            treeview.append_column(tvcolumn)
            cell = gtk.CellRendererText()
            #cell.set_property('cell-background', 'cyan')
            tvcolumn.pack_start(cell, True)
            tvcolumn.set_attributes(cell, text=i)
            tvcolumn.set_sort_column_id(i)
            i +=1
        
        treeview.set_search_column(0)
        treeview.set_reorderable(True)
        
    def row_expanded(self, treeview, treeiter, path):
        treestore = treeview.get_model()
        obj = treestore.get_value(treeiter, 2)

        if obj == None:
            return
        
        if len(path) <= 1:
            referrers = obj
        else:
            gc.collect()
            referrers = gc.get_referrers(obj)

        loading = treestore.iter_children(treeiter)
        for ref in referrers:
            if inspect.isframe(ref):
                continue
            elif isinstance(ref, list):
                if len(ref) > 1000:
                    continue
            if isinstance(id(ref), long):
                continue

            child = treestore.append(treeiter, [str(ref)[0:80], id(ref), ref])
            treestore.append(child, ["Loading", 0, None])
        treestore.remove(loading)

    def change_info_refresh_rate(self, hscale):
        self._refresh_rate = hscale.get_value()
        self.debug("refresh rate changed to %s" %  self._refresh_rate)
        
    def toggle_info_refresh(self, checkbox):
        self._auto_refresh = checkbox.get_active()
        self.debug("refresh checkbox changed to %s" % self._auto_refresh)
        if self._auto_refresh:
            reactor.callLater(self._refresh_rate, self.refresh)
            
    def toggle_use_snapshots(self, checkbox):
        self._use_snapshots = checkbox.get_active()
        self.debug("_use_snapshots changed to %s" % self._use_snapshots)
        

    def take_snapshot_clicked(self, bt):
        self.debug("take new snapshot")
        self._current_snapshot = self.report_tools.get_instance_infos()
    
    
    def combo_Snapshot_changed(self, c):
        self.debug("change snapshot combo")
        if c.get_active() == 0:
            self._use_startup_snapshot = True
        else:
            self._use_startup_snapshot = False
