class View(Base):
    __tablename__ = 'views'
    id = Column(Integer, primary_key = True)
    title = Column(String(30), nullable=False, index = True, unique = True, info={'label':_(u'Title')})
    link_name = Column(String(30), nullable=False, unique=True, info={'label':_(u'Link name')})
    link_title = Column(String(30), info={'label':_(u'Link title (linking)')})
    description = Column(Text(200), info={'label':_(u'Description')})
    datasource = Column(enum_col, nullable=False, info={'disabled': True, 'choices': datasource_choices, 'label':_(u'Datasource')})
    buttontext = Column(String(15), info={'label':_(u'Button text')})
    reload_intervall = Column(SmallInteger, nullable=False, info={'label':_(u'Browser reload')}, default=30)
    layout_number_columns = Column(SmallInteger, nullable=False, info={'label': _(u'Number of columns')}, default=3)
    basic_layout = Column(Enum('table','single'), default='table', info={'label': _(u'Basic layout'), 'choices': [('table', _('Table')), ('single',_('Single dataset'))]})
    filters_id = Column(Integer, ForeignKey(ViewFilters.id))

    filters = relationship(
        ViewFilters,
        backref = 'view'
    )

    def update_view(self, view):
        del view._sa_instance_state 
        #self.__dict__.update(view.__dict__)
        for attribute, value in view.__dict__.iteritems():
            setattr(self, attribute, value)
        '''
        self.title = view.title
        self.link_name = view.link_name
        self.datasource = view.datasource
        self.buttontext = view.buttontext
        self.reload_intervall = view.reload_intervall
        self.layout_number_columns = view.layout_number_columns
        ''' class ViewFilters(Base):
    __tablename__ = 'view_filters' 
    id = Column(Integer, primary_key=True)
    extra_filters = []

    def get_filters(self):
        """
        Create a dictionnary of filters and their values
        """
        filters_ret = {}
        for name, filt in filters.iteritems():
            option =  getattr(self, name + '_option')
            if option in [FILTER_SHOW, FILTER_HARD, FILTER_SHOW, FILTER_HIDE]:
                # If it is a hidden filters (linking), we consider it only if it come from an url
                if not option == FILTER_HIDE or name in self.extra_filters:
                    cols = filt.get_col_def()
                    if len(cols) > 1:
                        value_dict = {}
                        for col in filt.get_col_def():
                            value_dict[col.name] = getattr(self, col.name) 

                        filters_ret[filt.name] = value_dict 
                    else:
                        filters_ret[filt.name] = getattr(self, cols[0].name)
        return filters_ret

    def set_filters(self, filters):
        """
        Set class filter according to filters dictionnary, almost of the time coming from url parameters.
        """
        self.extra_filters = []
        for name, value in filters.iteritems():
            if not getattr(self, name + '_option') == FILTER_OFF:
                self.extra_filters.append(name)
                if type(value) == type(dict()):
                    for sub_name, sub_value in value.iteritems():
                        setattr(self, sub_name, sub_value)
                else:
                    setattr(self, name, value) 
            
    def update(self, filters):
        if hasattr(filters, '_sa_instance_state'):
            del filters._sa_instance_state 
        for attribute, value in filters.__dict__.iteritems():
            setattr(self, attribute, value) class ViewSorter(Base):
    __tablename__ = 'view_sorter'
    id = Column(Integer, primary_key=True)
    column = Column(enum_col, info={'choices':column_choices, 'label':_(u'Column')} )
    sorter_option = Column(enum_sorter_options, info={'choices':sorted(sort_option.items())})
    parent_id = Column(Integer, ForeignKey(View.id), nullable=False)
    view = relationship(
        View,
        backref = 'view_sorter'
    ) class ViewGrouper(Base):
    __tablename__ = 'view_grouper'
    id = Column(Integer, primary_key=True)
    column = Column(enum_col, info={'choices':column_choices, 'label':_(u'Column')} )
    parent_id = Column(Integer, ForeignKey(View.id), nullable=False)
    view = relationship(
        View,
        backref = 'view_grouper'
    ) FILTER_OFF = 'off'
FILTER_HARD = 'hard'
FILTER_SHOW = 'show'
FILTER_HIDE = 'hide'
class ViewFilters(Base):
    def get_filters(self):
    def set_filters(self, filters):
    def update(self, filters): def init_engine(db_uri):
def init_db():
def create_default_users():
def create_default_views():
def __add_column(name, view, link=""):
def __add_sort_by(name, view, order=""):
def __add_group_by(name, view):
def clear_db(): class ViewColumn(Base):
    __tablename__ = 'view_column'
    id = Column(Integer, primary_key=True)
    column = Column(enum_col, nullable=False, info={'choices':column_choices, 'label':_(u'Column')} )
    link = Column(String(30)) 
    parent_id = Column(Integer, ForeignKey(View.id), nullable=False)
    view = relationship(
        View,
        backref = 'view_column'
    ) def get_rows(datasource, columns_names, filters_string):
def query_data(datasource, columns, add_headers, filters_string, only_sites = [], limit = None):
def merge_data(data, columns):
    def worst_service_state(a, b):
    def worst_host_state(a, b): class FiltersManager():
    """ A sort of proxy that facilitates filters usage. There is one FiltersManager per view display.
    """   
    def __init__(self):
        self.__filters = {}

    def set_filters(self, filters):
        self.__filters = filters

    def get_filter_query(self):
        filter_query = ''
        for name, filter_value in self.__filters.get_filters().iteritems():
            if filter_value:
                filter_query = filter_query + filters[name].filter(filter_value)             

        return filter_query
    
    def get_filters_name(self):
        return filters.keys() COL_HOST_NAME = 'host_name'
COL_HOST_STATE = 'host_state'
COL_SERVICE_STATE = 'service_state'
COL_LAST_CHECK = 'last_check'
COL_CHECK_COMMAND = 'check_command'
COL_SITE = 'site'
COL_SERVICE_DESCRIPTION = 'service_description'
COL_SERVICE_PLUGIN_OUTPUT = 'service_plugin_output'
COL_STATE_TYPE = 'state_type'
COL_OUTPUT = 'plugin_output'
COL_NUM_SERVICES_OK = 'num_services_ok'
COL_NUM_SERVICES_WARN = 'num_services_warn'
COL_NUM_SERVICES_CRIT = 'num_services_crit'
COL_NUM_SERVICES_UNKNOWN = 'num_services_unknown'
COL_NUM_SERVICES_PENDING = 'num_services_pending'
COL_HOST_IN_NOTIFICATION_PERIOD = 'host_in_notification_period'
COL_SERVICE_IN_NOTIFICATION_PERIOD = 'service_in_notification_period'
COL_HOST_ACKNOWLEDGED = 'host_acknowledged'
COL_HOST_SCHEDULED_DOWNTIME_DEPTH = 'host_scheduled_downtime_depth'
COL_SERVICE_SCHEDULED_DOWNTIME_DEPTH = 'service_scheduled_downtime_depth'
COL_HOST_CUSTOM_VARIABLE_NAMES = 'host_custom_variable_names'
COL_SERVICE_ACKNOWLEDGED = 'service_acknowledged'
def get_columns_pairs(datasources=None):
def get_columns_name(datasources=None):
def get_datasources_available(): class FilterFieldsInfo():
    def __init__(self, option_field, fields):
        self.option_field = option_field
        self.fields = fields OP_EQUAL = '='
OP_TILDE = '~~'
FILTER_HOSTREGEX = 'host_regex'
FILTER_HOST_EXACT_MATCH = 'host'
FILTER_SERVICE_EXACT_MATCH = 'service'
FILTER_HOST_STATE = 'host_state'
FILTER_SERVICE_STATE = 'service_state'
FILTER_IS_SUMMARY_HOST = 'is_summary_host'
FILTER_SITE = 'site'
FILTER_IS_HOST_ACKNOWLEDGED = 'is_host_acknowledged'
FILTER_IS_SERVICE_ACKNOWLEDGED = 'is_service_acknowledged'
FILTER_IS_HOST_IN_NOTIFICATION_PERIOD = 'is_host_in_notification_period'
FILTER_IS_SERVICE_IN_NOTIFICATION_PERIOD = 'is_service_in_notification_period'
FILTER_IS_HOST_SCHEDULED_DOWNTIME_DEPTH = 'is_host_scheduled_downtime_depth'
FILTER_IS_SERVICE_SCHEDULED_DOWNTIME_DEPTH = 'is_service_scheduled_downtime_depth' COL_HOST_NAME = 'host_name'
COL_HOST_STATE = 'host_state'
COL_SERVICE_STATE = 'service_state'
COL_LAST_CHECK = 'last_check'
COL_CHECK_COMMAND = 'check_command'
COL_SITE = 'site'
COL_SERVICE_DESCRIPTION = 'service_description'
COL_SERVICE_PLUGIN_OUTPUT = 'service_plugin_output'
COL_STATE_TYPE = 'state_type'
COL_OUTPUT = 'plugin_output'
COL_NUM_SERVICES_OK = 'num_services_ok'
COL_NUM_SERVICES_WARN = 'num_services_warn'
COL_NUM_SERVICES_CRIT = 'num_services_crit'
COL_NUM_SERVICES_UNKNOWN = 'num_services_unknown'
COL_NUM_SERVICES_PENDING = 'num_services_pending'
COL_HOST_IN_NOTIFICATION_PERIOD = 'host_in_notification_period'
COL_SERVICE_IN_NOTIFICATION_PERIOD = 'service_in_notification_period'
COL_HOST_ACKNOWLEDGED = 'host_acknowledged'
COL_HOST_SCHEDULED_DOWNTIME_DEPTH = 'host_scheduled_downtime_depth'
COL_SERVICE_SCHEDULED_DOWNTIME_DEPTH = 'service_scheduled_downtime_depth'
COL_HOST_CUSTOM_VARIABLE_NAMES = 'host_custom_variable_names'
COL_SERVICE_ACKNOWLEDGED = 'service_acknowledged'
def get_columns_pairs(datasources=None):
def get_columns_name(datasources=None):
def get_datasources_available():
from app.db_model.view import View
from app.db_model.viewFilters import ViewFilters
from app.db_model.viewSorter import ViewSorter
from app.db_model.viewGrouper import ViewGrouper
from app.db_model.viewFilters import cache_columns
from app.db_model.base import db_session
from app.db_model.viewColumn import ViewColumn
from app.lib import livestatus_query
from app.lib.datasources import multisite_datasources as datasources
from app.managers.filters_manager import FiltersManager
from app.model.columns.builtin import painters, get_columns_pairs
from app.model.filters.filter_fields_info import FilterFieldsInfo
from app.model.filters.builtin import filters
from app.model.columns.builtin import painters
import copy
#   
#   Copyright (C) 2013 Savoir-Faire Linux Inc.
#   
#   This file is part of Sageo
#   
#   Sageo is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   Sageo is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with Sageo.  If not, see <http://www.gnu.org/licenses/>



class ViewManager():
    """ A sort of proxy that facilitate views modification and views queries. """
    def __init__(self):
        self.__view = None
        self.__columns = None 
        self.__groupers = None
        self.__sorters = None
        self.__filters = None
    '''
    Set the view with the link_name. If a view is found, return the view found 
    '''
    def set_view(self, link_name):
        self.__view = View.query.filter_by(link_name=link_name).first()
        if self.__view:
            self.__columns = ViewColumn.query.filter_by(parent_id=self.__view.id).order_by(ViewColumn.id).all()

            self.__groupers = ViewGrouper.query.filter_by(parent_id=self.__view.id).order_by(ViewGrouper.id).all()