# vim: ts=4 et sts=4 sw=4 autoindent

import gtk
import Pyro.core

from sndcs_common.PyroProxyMixin import PyroProxyMixin
from sndcs_client.Config import config

# Searching function
from Application import treeview_visible_function

from sndcs_common.Logger import logger
log = logger.getLogger("sndcs_gtk")

def _(input):
    if not input: return "N/A"
    else: return input


class AvailableActivitiesTreeView(PyroProxyMixin):

    def __init__(self, tree_view, multiple = True, namespace=None):
        self.view = tree_view
        # If multiple is True allow multiple selections
        if multiple:
            selection = self.view.get_selection()
            selection.set_mode(gtk.SELECTION_MULTIPLE)
        tree_column_1 = gtk.TreeViewColumn("Job")
        tree_column_2 = gtk.TreeViewColumn("Assembly")
        tree_column_3 = gtk.TreeViewColumn("Operation")
        tree_column_4 = gtk.TreeViewColumn("Description")
        tree_column_5 = gtk.TreeViewColumn("Priority")
        tree_column_6 = gtk.TreeViewColumn("Department")
        tree_column_1.set_sort_column_id(1)
        tree_column_2.set_sort_column_id(2)
        tree_column_3.set_sort_column_id(3)
        tree_column_4.set_sort_column_id(4)
        tree_column_5.set_sort_column_id(5)
        tree_column_6.set_sort_column_id(6)
        self.view.append_column(tree_column_1)
        self.view.append_column(tree_column_2)
        self.view.append_column(tree_column_3)
        self.view.append_column(tree_column_4)
        self.view.append_column(tree_column_5)
        self.view.append_column(tree_column_6)
        cell = gtk.CellRendererText()
        tree_column_1.pack_start(cell, True)
        tree_column_1.add_attribute(cell, "text", 1)
        tree_column_2.pack_start(cell, True)
        tree_column_2.add_attribute(cell, "text", 2)
        tree_column_3.pack_start(cell, True)
        tree_column_3.add_attribute(cell, "text", 3)
        tree_column_4.pack_start(cell, True)
        tree_column_4.add_attribute(cell, "text", 4)
        tree_column_5.pack_start(cell, True)
        tree_column_5.add_attribute(cell, "text", 5)
        tree_column_6.pack_start(cell, True)
        tree_column_6.add_attribute(cell, "text", 6)

        self.model = gtk.ListStore(long, str, str, str, str, int, str)

        self.view.set_model(self.model)
        self.column_number = 0
        self.search_criteria = ""

        if namespace:
            self.namespace = namespace
        else:
            # Get the Pyro namespace from the config
            self.namespace = config.get("pyro", "namespace", "sndcs")


    def treeview_department_function(self,model,iter,departments):
        value=str(model.get_value(iter,6))
        if value<>"N/A":
            if value in departments:
                return True # Display
            else:
                return False
        else: return True # Display



    def populate(self, model=None):
        """Populate the model"""
        if model:
            self.model = model
        else:
            self.model = gtk.ListStore(long, str, str, str, str, int, str)

            available_activities = Pyro.core.getProxyForURI(self.formatPyronameString(self.namespace, ["Operation"]))

            activities =  available_activities.getAvailableActivitiesData()
            for activity in activities:
                try:
                    priority = int(activity["priority"])
                except:
                    priority = 0

                self.model.append((activity["operation_id"], activity["job"], activity["assembly"], activity["operation"], activity["description"], priority, _(activity["department"])))

        self.modelfilter = self.model.filter_new()
        self.modelfilter.set_visible_func(treeview_visible_function,self)

        self.modelsort = gtk.TreeModelSort(self.modelfilter)

        self.view.set_model(self.modelsort)
        self.modelsort.set_sort_column_id(1, gtk.SORT_DESCENDING) # Start off sorting by the first column DESCENDING
        return self.model

    def find_operation(self, operation_id):
        p = None # (p)arent
        i = 0

        for x in self.model:
            if int(x[0]) == int(operation_id):
                p = i
                break
            i += 1
        return p

    def add_operation(self, operation_id, job_num, assembly_num, op_num, description, priority, department):
        self.model.append((operation_id, job_num, assembly_num, op_num, description, priority, _(department)))
    
    def delete_operation(self, operation_id): # Operation was completed/deleted
        p = self.find_operation(operation_id)
        if p is not None:
            parent_iter = self.model.get_iter(p)
            self.model.remove(parent_iter)

    def update(self, event=False, departments=None):
        if event:
            if event.subject == self.namespace + "_operation_add":
                operation_id = event.msg["serialNum"]
                job_num = event.msg["job"]
                assembly_num = event.msg["assembly"]
                op_num = event.msg["operation"]
                description = event.msg["description"]
                priority = event.msg["priority"]
                department = event.msg["department"]

                log.info("[%s - %s - %s ] Operation added" % (job_num, assembly_num,op_num) )
                self.add_operation(operation_id, job_num, assembly_num, op_num, description, priority, department)
            elif event.subject == self.namespace + "_operation_delete":
                operation_id = event.msg["serialNum"]
                assembly = event.msg["assembly"]

                log.info("[%s(serialNum) - %s(serialNum) ] Operation deleted" % (assembly,operation_id) )
                self.delete_operation(operation_id)
            elif event.subject == self.namespace + "_operation_complete":
                operation_id = event.msg["serialNum"]
                assembly_num = event.msg["assembly"]
                op_num = event.msg["operation"]

                log.info("[%s - %s ] Operation complete" % (assembly_num,op_num) )
                self.delete_operation(operation_id)
        elif departments:
            self.modeldepartments = self.modelfilter.filter_new()
            self.modeldepartments.set_visible_func(self.treeview_department_function,departments)

            self.modelsorting = gtk.TreeModelSort(self.modeldepartments)

            self.view.set_model(self.modelsorting)
            self.modelsorting.set_sort_column_id(1, gtk.SORT_DESCENDING) 
        
        self.modelfilter.refilter()
        if hasattr(self,"modeldepartments"): # Has to be a better way to do this!?
            self.modeldepartments.refilter() 

