Ext.define('TP.formFilter', {
    extend: 'Ext.panel.Panel',

    alias:  'widget.tp_filter',

    layout: {
        type: 'table',
        columns: 2
    },
    border: 0,
    items: [{
        xtype:      'textfield',
        name:       'name',
        value:      '',
        width:      100
    }, {
        xtype:     'button',
        text:      'Change Filter',
        icon:      '[% url_prefix %]thruk/plugins/panorama/images/image_edit.png',
        handler:   function() { TP.filterWindow(this.up('panel').ftype, this.up('panel').items.getAt(0)); }
    }],

    initComponent: function() {
        this.callParent();
        this.items.getAt(0).fieldLabel = this.fieldLabel;
        this.items.getAt(0).value      = this.value;
        this.items.getAt(0).name       = this.name;
        this.addListener('afterrender', function() {
            this.items.getAt(0).inputEl.hide();
        });
    }
});

Ext.define('TP.formFilterSelect', {
    extend: 'Ext.panel.Panel',

    alias:  'widget.tp_filter_select',

    border: false,
    layout:     {
            type: 'table',
            columns: 5,
            tableAttrs: {
                style: {
                    width: '100%'
                }
            }
    },
    items:      [{
        name:           'type',
        xtype:          'combobox',
        queryMode:      'local',
        editable:       false,
        triggerAction:  'all',
        forceSelection: true,
        autoSelect:     true,
        width:          140,
        store:          ['Search',
                         'Check Period',
                         'Comment',
                         'Contact',
                         'Current Attempt',
                         'Custom Variable',
                         'Downtime Duration',
                         'Duration',
                         'Execution Time',
                         'Host',
                         'Hostgroup',
                         'Last Check',
                         'Latency',
                         'Next Check',
                         'Notification Period',
                         'Parent',
                         'Service',
                         'Servicegroup',
                         '% State Change'],
        listeners: {
            change: function(This, newV, oldV, eOpts) {
                /* update value store */
                var panel = This.up('panel');
                newV = newV.toLowerCase();
                var combo = panel.items.getAt(3);
                combo.store.removeAll();
                if(newV == 'host' || newV == 'service' || newV == 'hostgroup' || newV == 'servicegroup' || newV == 'check period' || newV == 'notification period') {
                    var type = newV;
                    if(newV == 'check period' || newV == 'notification period') {
                        type = 'timeperiod';
                    }
                    var url = 'status.cgi?format=search&hash=1&type='+type;
                    Ext.Ajax.request({
                        url: url,
                        method: 'POST',
                        callback: function(options, success, response) {
                            var tmp  = TP.getResponse(undefined, response);
                            if(tmp) {
                                TP.updateArrayStore(combo.store, tmp[0].data);
                            }
                        }
                    });
                }
                panel.check_changed(newV);
            }
        }
    }, {
        name:           'val_pre',
        xtype:          'textfield',
        width:          100,
        value:          [],
        tooltip:        'Name of the custom variable. e.x: VAR1 (without the underline)'
    }, {
        name:           'op',
        xtype:          'combobox',
        queryMode:      'local',
        editable:       false,
        triggerAction:  'all',
        forceSelection: true,
        autoSelect:     true,
        width:          50,
        store:          ['~','!~','=','!=','<=','>=']
    }, {
        name:           'value',
        xtype:          'combobox',
        width:          182,
        store:          []
    }, {
        xtype:          'datetimefield',
        name:           'value_date'
    }, {
        xtype:      'panel',
        border:     false,
        width:      14,
        html:       '<div align="center" class="clickable"><img src="[% url_prefix %]thruk/plugins/panorama/images/remove.png" alt="remove filter" style="vertical-align: top"><\/div>',
        listeners:  {
            afterrender: function(This, eOpts) { This.body.on('click', function() {
                var row = This.up('panel');
                var form = This.up('panel').up('form');
                form.remove(row);
            })}
        }
    }],

    /* check datetime or input field */
    check_changed: function(v) {
        if(!this.items.getAt(1).rendered || !this.items.getAt(3).rendered || !this.items.getAt(4).rendered) {
            return;
        }
        v = v.toLowerCase();
        if(v == 'last check' || v == 'next check') {
            this.items.getAt(1).hide();
            this.items.getAt(3).hide();
            this.items.getAt(4).show();
        } else {
            this.items.getAt(1).hide();
            this.items.getAt(3).show();
            this.items.getAt(4).hide();
        }
        if(v == 'custom variable') {
            this.items.getAt(1).show();
        }
        var op = this.items.getAt(2).getValue();

        var ops = {
            'search':              ['~','!~','=','!='],
            'check period':        ['~','!~','=','!='],
            'comment':             ['~','!~','=','!='],
            'contact':             ['~','!~','=','!='],
            'current attempt':     ['=','!=','<=','>='],
            'custom variable':     ['~','!~','=','!='],
            'downtime duration':   ['=','!=','<=','>='],
            'duration':            ['=','!=','<=','>='],
            'execution time':      ['=','!=','<=','>='],
            'host':                ['~','!~','=','!='],
            'hostgroup':           ['~','!~','=','!='],
            'last check':          ['=','!=','<=','>='],
            'latency':             ['=','!=','<=','>='],
            'next check':          ['=','!=','<=','>='],
            'notification period': ['~','!~','=','!='],
            'parent':              ['~','!~','=','!='],
            'service':             ['~','!~','=','!='],
            'servicegroup':        ['~','!~','=','!='],
            '% state change':      ['=','!=','<=','>=']
        };

        TP.updateArrayStore(this.items.getAt(2).store, ops[v], op);
        this.items.getAt(2).setValue(op);
        if(this.items.getAt(2).getValue() == null) {
            this.items.getAt(2).setRawValue(ops[v][0]);
        }
    },

    initComponent: function() {
        this.callParent();
        this.items.getAt(0).setValue(this.val_type  || 'Search');
        this.items.getAt(1).setValue(this.val_pre   || '');
        this.items.getAt(2).setValue(this.val_op    || '~');
        this.items.getAt(3).setValue(this.val_value || '');
        if(this.val_val_d) {
            var d = Date.parse(this.val_val_d);
            this.items.getAt(4).setValue(new Date(d));
        } else {
            this.items.getAt(4).setValue(new Date());
        }

        this.addListener('afterrender', function(This, eOpts) {
            // has to be hidden after renderer, otherwise show does not work
            This.check_changed(This.items.getAt(0).getValue());
        });
    }
});

TP.filterWindow = function(ftype, base_el) {

    var form = new Ext.form.Panel({
            bodyPadding: 3,
            defaults: {
                labelWidth: 120
            },
            items: [{
                    fieldLabel: 'Host Status Types',
                    name:       'hoststatustypes',
                    xtype:      'tp_combobox_sum',
                    width:      373,
                    value:      [1,2,4,8],
                    sum_values: {'15': 'All', '12': 'All Problems' },
                    store:      [[2,'Up'], [4,'Down'], [8,'Unreachable'], [1,'Pending']]
                }, {
                    fieldLabel: 'Host Properties',
                    name:       'hostprops',
                    xtype:      'tp_combobox_sum',
                    width:      373,
                    columns:    true,
                    value:      [],
                    sum_values: {'0': 'Any' },
                    store:      [[1,'In Scheduled Downtime'], [2,'Not In Scheduled Downtime'],
                                 [4,'Has Been Acknowledged'], [8,'Has Not Been Acknowledged'],
                                 [16,'Checks Disabled'], [32,'Checks Enabled'],
                                 [64,'Event Handler Disabled'], [128,'Event Handler Enabled'],
                                 [256,'Flap Detection Disabled'], [512,'Flap Detection Enabled'],
                                 [1024,'Is Flapping'], [2048,'Is Not Flapping'],
                                 [4096,'Notifications Disabled'], [8192,'Notifications Enabled'],
                                 [16384,'Passive Checks Disabled'], [32768,'Passive Checks Enabled'],
                                 [65536,'Passive Checks'], [131072,'Active Checks'],
                                 [262144,'In Hard State'], [524288,'In Soft State'],
                                 [1048576,'In Check Period'], [2097152,'Outside Check Period'],
                                 [4194304,'In Notification Period'], [8388608,'Outside Notification Period'],
                                 [16777216,'Has Modified Attributes'], [33554432,'No Modified Attributes']]
                }, {
                    fieldLabel: 'Service Status Types',
                    name:       'servicestatustypes',
                    xtype:      'tp_combobox_sum',
                    width:      373,
                    value:      [1,2,4,8,16],
                    sum_values: {'31': 'All', '28': 'All Problems' },
                    store:      [[2,'Ok'],[4,'Warning'],[8,'Unknown'],[16,'Critical'],[1,'Pending']]
                }, {
                    fieldLabel: 'Service Properties',
                    name:       'serviceprops',
                    xtype:      'tp_combobox_sum',
                    width:      373,
                    columns:    true,
                    value:      [],
                    sum_values: {'0': 'Any' },
                    store:      [[1,'In Scheduled Downtime'], [2,'Not In Scheduled Downtime'],
                                 [4,'Has Been Acknowledged'], [8,'Has Not Been Acknowledged'],
                                 [16,'Active Checks Disabled'], [32,'Active Checks Enabled'],
                                 [64,'Event Handler Disabled'], [128,'Event Handler Enabled'],
                                 [512,'Flap Detection Disabled'], [256,'Flap Detection Enabled'],
                                 [1024,'Is Flapping'], [2048,'Is Not Flapping'],
                                 [4096,'Notifications Disabled'], [8192,'Notifications Enabled'],
                                 [16384,'Passive Checks Disabled'], [32768,'Passive Checks Enabled'],
                                 [65536,'Passive Checks'], [131072,'Active Checks'],
                                 [262144,'In Hard State'], [524288,'In Soft State'],
                                 [1048576,'In Check Period'], [2097152,'Outside Check Period'],
                                 [4194304,'In Notification Period'], [8388608,'Outside Notification Period'],
                                 [16777216,'Has Modified Attributes'], [33554432,'No Modified Attributes']]
                }, {
                    xtype:      'panel',
                    border:     false,
                    html:       '<div align="center"><div class="clickable" style="width: 40px;"><img src="[% url_prefix %]thruk/plugins/panorama/images/down.png" alt="add new filter" style="vertical-align: middle"> and<\/div><\/div>',
                    listeners:  {
                        afterrender: function(This, eOpts) { Ext.get(This.body.dom.firstChild.firstChild).on('click', function() {
                            var form = This.up('form');
                            form.insert(form.items.length-1, {xtype: 'tp_filter_select'});
                        })}
                    }
            }],
            buttonAlign: 'center',
            fbar: [{ xtype:  'button', text: 'cancel', handler: function() { this.up('window').destroy() } },
                   { xtype:  'button',
                     text:    'save',
                     handler: function(This) {
                        var form = This.up('panel').getForm();
                        var vals = form.getFieldValues();
                        vals.hostprops          = TP.arraySum(vals.hostprops);
                        vals.serviceprops       = TP.arraySum(vals.serviceprops);
                        vals.hoststatustypes    = TP.arraySum(vals.hoststatustypes);
                        vals.servicestatustypes = TP.arraySum(vals.servicestatustypes);
                        base_el.setValue(Ext.JSON.encode(vals));
                        this.up('window').destroy();
                     }
            }]
    });

    var win = new Ext.window.Window({
        title:      'Filter',
        layout:     'fit',
        modal:       true,
        maximizable: true,
        items:       [form]
    });

    /* hide service specific fields for hosts */
    if(ftype == 'host') {
        form.items.getAt(2).hide();
        form.items.getAt(3).hide();
    }

    /* add values */
    var val = base_el.getValue();
    if(val) {
        val = Ext.JSON.decode(val);
        var values = {
            hoststatustypes:    TP.dec2bin(val.hoststatustypes),
            hostprops:          TP.dec2bin(val.hostprops),
            servicestatustypes: TP.dec2bin(val.servicestatustypes),
            serviceprops:       TP.dec2bin(val.serviceprops)
        };
        if(Ext.isArray(val.type)) {
            for(var nr in val.type) {
                form.insert(form.items.length-1, {
                    xtype:     'tp_filter_select',
                    val_op:     val.op[nr],
                    val_type:   val.type[nr],
                    val_pre:    val.val_pre[nr],
                    val_value:  val.value[nr],
                    val_val_d:  val.value_date[nr]
                });
            }
        } else {
            form.insert(form.items.length-1, {
                xtype:     'tp_filter_select',
                val_op:     val.op,
                val_type:   val.type,
                val_pre:    val.val_pre,
                val_value:  val.value,
                val_val_d:  val.value_date
            });
        }
        form.getForm().setValues(values);
    } else {
        /* add one empty search field */
        form.insert(form.items.length-1, {xtype: 'tp_filter_select'});
    }

    /* show the window */
    win.show();
}
