Ext.define("App.view.Viewport", {
    extend: "Ext.container.Viewport",
    alias: "widget.Viewport",
    resetFocusPosition: true,
    focusable:true,
    requires: ["Ext.button.Segmented", "Ext.list.Tree"],

    itemId: "mainView",

    layout: {
        type: "vbox",
        align: "stretch"
    },

    onToggleNavigationSize: function() {
        var me = this;
        var navigationList = me.down("#navigationTreeList");
        var wrapContainer = me.down("maincontainerwrap");
        var navTreePanel = me.down("#navTreePanel");
        var senchaLogo = me.down("toolbar").down("#senchaLogo");
        var collapsing = !navigationList.getMicro();
        var new_width = collapsing ? 64 : 200;

        if (Ext.isIE9m || !Ext.os.is.Desktop) {
            Ext.suspendLayouts();
            senchaLogo.setWidth(new_width);

            navTreePanel.setWidth(new_width);
            navigationList.setMicro(collapsing);
            navigationList.el.addCls("nav-tree-animating");

            Ext.resumeLayouts(); // do not flush the layout here...

            // No animation for IE9 or lower...
            wrapContainer.layout.animatePolicy = wrapContainer.layout.animate = null;
            wrapContainer.updateLayout(); // ... since this will flush them
        } else {
            if (!collapsing) {
                // If we are leaving micro mode (expanding), we do that first so that the
                // text of the items in the navlist will be revealed by the animation.
                navigationList.setMicro(false);
            }
            navigationList.canMeasure = false;

            // Start this layout first since it does not require a layout
            senchaLogo.animate({ dynamic: true, to: { width: new_width } });

            // Directly adjust the width config and then run the main wrap container layout
            // as the root layout (it and its chidren). This will cause the adjusted size to
            // be flushed to the element and animate to that new size.
            navTreePanel.setWidth(new_width);
            navigationList.setMicro(collapsing);
            wrapContainer.updateLayout({ isRoot: true });
            navigationPanel.el.addCls("nav-tree-animating");

            // We need to switch to micro mode on the navlist *after* the animation (this
            // allows the "sweep" to leave the item text in place until it is no longer
            // visible.
            if (collapsing) {
                navigationPanel.on({
                    afterlayoutanimation: function() {
                        navigationList.setMicro(true);
                        navigationPanel.el.removeCls("nav-tree-animating");
                        navigationPanel.canMeasure = true;
                    },
                    single: true
                });
            }
        }
    },
    items: [
        {
            xtype: "toolbar",
            height: 64,
            padding: 0,
            itemId: "headerBar",
            style: {
                "background-color": "#87CEFA"
            },
            items: [
                {
                    xtype: "container",
                    id: "senchaLogo",
                    itemId: "senchaLogo",
                    name: "senchaLogo",
                    cls: "sencha-logo",
                    width: 200,
                    layout:"hbox",
                    items: [
                        {
                            xtype: "component",
                            html:
                                '<div class="main-logo"><img src= "' +
                                App.url("/resources/images/login_logo.png") +'"'+
                                " width='37' height='26'></div>",
                        },
                        {
                            xtype: "component",
                            flex:1,
                        },
                        {
                            xtype: 'splitbutton',
                            itemId: 'languageBtn',
                            margin:0,
                            padding:0,
                            ui: 'default-toolbar',
                            height: '100%',
                            minWidth: 64,
                            handler: function(button) {
                                button.showMenu();
                            },
                            onMenuItemClick: function(item){
                                Ext.Ajax.request({
                                    url: App.url("/user/setting/save"),
                                    params: { 
                                        name: "USER_lang",
                                        value: item.code
                                    },
                                    success: function(response, opts) {
                                        window.location.reload(true);
                                    },
                                    failure: function(response, opts) {
                                        App.showError('Message : ' + response.status);
                                    },
                                    scope: this
                                });
                            },
                            menu: new Ext.menu.Menu({
                                items: [
                                    {text: App.getLocaleStr('en'), code:"en", handler: function(){ this.getBubbleParent().onItemClick(this)}},
                                    {text: App.getLocaleStr('zh_TW'), code:"zh_TW", handler: function(){ this.getBubbleParent().onItemClick(this)}},
                                    {text: App.getLocaleStr('zh_CN'), code: "zh_CN",handler: function(){ this.getBubbleParent().onItemClick(this)}}
                                ],
                                onItemClick: function(item){
                                    this.getBubbleParent().onMenuItemClick(item);
                                }
                            })
                        },
                    ]
                },
                {
                    margin: "0 0 0 8",
                    ui: "header",
                    iconCls: "x-fa fa-navicon",
                    id: "main-navigation-btn",
                    handler: function() {
                        this.up("viewport").onToggleNavigationSize();
                    }
                },
                {
                    xtype: "label",
                    itemId: "containerTitle",
                    listeners: {
                        render: function(label){
                            label.setHtml("<div class='container-title'>"+App.getTitle(Ext.History.hash)+"</div>")
                        }
                    }
                },
                "->",
                {
                    xtype: "segmentedbutton",
                    margin: "0 16 0 0",
                    ui: "header",
                    platformConfig: {
                        ie9m: {
                            hidden: true
                        }
                    }
                },
                // {
                //     iconCls: "x-fa fa-pencil-square-o",
                //     ui: "header",
                //     tooltip: App.localeRes("Compose Message"),
                //     handler: function() {
                //         App.loadModuleWin("composeMessageWindow");
                //     }
                // },
                {
                    xtype: "button",
                    ui: "header",
                    text:  "<font style='color:white; font-family:sans-serif;' size='+0.5'><u>" + App.fullname+"</u></font>",
                    tooltip: App.localeRes('Change password'),
                    handler: function (button, event) {
                        App.loadModuleWin('userChangePasswordWindow',App.localeRes('Change password'));
                    }
                },
                {
                    xtype: 'tbseparator'
                },
                {
                    xtype: "button",
                    iconCls: "x-fa fa-bell",
                    itemId: 'remindBtn',
                    ui: "header",
                    hidden: true,
                    text: "<b><font style='color:white; font-family:sans-serif;'>(0)</font></b>",
                    tooltip: App.localeRes("Remind"),
                    handler: function(button, event) {
                        App.loadModuleWin('remindWindow', App.localeRes("Remind"), {
                            callbackOnClose: function () {
                                Ext.Ajax.request({
                                    url: App.url("/message/new"),
                                    success: function(response, opts) {
                                        var result = Ext.decode(response.responseText);
                                        button.setText("<b><font style='color:white; "
                                        +" font-family:sans-serif;'>("+result.new+")</font></b>");
                                    },
                                    failure: function(response, opts) {},
                                    scope: this
                                });
                            }
                        });
                    }
                },
                '-',
                {
                    xtype: "button",
                    iconCls: "x-fa fa-sign-out fa-2x",
                    iconAlign: 'top',
                    ui: "header",
                    text: "<b><font style='color:white; font-family:sans-serif;'>"+App.localeRes("Log Out")+"</font></b>",
                    tooltip: App.localeRes("Log Out"),
                    handler: function() {
                        App.logout();
                    }
                }
               
            ]
        },
        {
            xtype: "maincontainerwrap",
            id: "main-view-detail-wrap",
            reference: "mainContainerWrap",
            flex: 1,
            items: [
                {
                    xtype: "container",
                    width: 200,
                    reference: "navTreePanel",
                    itemId: "navTreePanel",
                    style: "overflow:hidden",
                    layout: "absolute",
                    items: [
                        {
                            x: 0,
                            y: 0,
                            anchor: "+17 0",
                            xtype: "treelist",
                            reference: "navigationTreeList",
                            itemId: "navigationTreeList",
                            ui: "nav",
                            store: Ext.create("App.store.NavigationTreeStore", {}),
                            width: 190,
                            style: {
                                "overflow-y": "scroll",
                                "padding-top": "10px",
                                "padding-down": "10px",
                            },
                            expanderFirst: false,
                            expanderOnly: false,
                            listeners: {
                                selectionchange: function(tree, node) {
                                    var me = this;
                                    var to = node && node.get("viewType");
                                    var title = node && node.get("title");
                                    console.log(title);
                                    if (to) {
                                        App.loadModuleDash(to);
                                        App.addHistory(to);
                                        titleContainer = me
                                            .up()
                                            .up()
                                            .up()
                                            .down("#headerBar")
                                            .down("#containerTitle");
                                        titleContainer.setHtml("<div class='container-title'>" + title + "</div>");
                                    }
                                },
                                renderer: function(val, meta, rec) {
                                    meta.tdAttr = 'data-qtip="This is my tooltip"';
                                    return val;
                                }
                            },
                        },
                    ],
                },
                {
                    xtype: "container",
                    flex: 1,
                    id: "mainContainer",
                    reference: "mainCardPanel",
                    cls: "sencha-dash-right-main-container",
                    itemId: "contentPanel",
                    scrollable: true,
                    layout: {
                        type: "card",
                        anchor: "100%"
                    }
                }
            ]
        }
    ],
    onChangeLocale: function(locale) {
		Ext.Ajax.request({
			method: 'GET',
			url: '<@spring.url "/locale" />',
			params:	{ locale: locale },
			
			success: function(response, opts) {
				var obj = Ext.decode(response.responseText);
				location.reload(); 
			},
		
			failure: function(response, opts) {
				console.log('server-side failure with status code ' + response.status);
			}
		});
	},
    listeners: {
        render: function(viewport, eOpts) {
            if(Ext.History.hash){
                App.addHistory(Ext.History.hash);
            }else{
                App.addHistory("calendarContainer");
            }

            Ext.Ajax.request({
                url: App.url("/user/get-settings"),
                success: function(response, opts) {
                    var result = Ext.decode(response.responseText);
                    App.initUserSetting(result.records)
                    App.setLocale(App.getUserSetting("USER_lang"))
                },
                failure: function(response, opts) {},
                scope: this
            });

            // <#-- ajax ping to get unread msg -->
            if(App.isGranted(["AMOUNT_REMIND"])){
                viewport.down('#remindBtn').setHidden(false);
                viewport.down('tbseparator').setHidden(false);
                viewport.loadMsgTask = App.runTask(function() {
                    Ext.Ajax.request({
                        url: App.url("/message/new"),
                        success: function(response, opts) {
                            var result = Ext.decode(response.responseText);
                            viewport.down('#remindBtn').setText("<b><font style='color:white; "
                            +" font-family:sans-serif;'>("+result.new+")</font></b>");
                        },
                        failure: function(response, opts) {},
                        scope: this
                    });
                }, 10000);
                
            }else{
                viewport.down('#remindBtn').setHidden(true);
                viewport.down('tbseparator').setHidden(true);
                if(viewport.loadMsgTask){
                    App.stopTask(viewport.loadMsgTask, true);
                    viewport.loadMsgTask = "";
                }
            }
        },
        resize: function() {}
    }
});

Ext.define('override.grid.CellContext', {
    override: 'Ext.grid.CellContext',
    
        setRow: function(row) {
        var me = this,
            dataSource = me.view.dataSource,
            oldRecord = me.record,
            count;
        
        if (row !== undefined && row !== null) {
            // Row index passed, < 0 meaning count from the tail (-1 is the last, etc) 
            if (typeof row === 'number') {
                count = dataSource.getCount();
                row = row < 0 ? Math.max(count + row, 0) : Math.max(Math.min(row, count - 1), 0);
                
                me.rowIdx = row;
                me.record = dataSource.getAt(row);
            }
            // row is a Record 
            else if (row.isModel) {
                me.record = row;
                me.rowIdx = dataSource.indexOf(row);
            }
            // row is a grid row, or Element wrapping row 
            else if (row.tagName || row.isElement) {
                me.record = me.view.getRecord(row);
 
                // If it's a placeholder record for a collapsed group, index it correctly 
                me.rowIdx = me.record ? (me.record.isCollapsedPlaceholder ? dataSource.indexOfPlaceholder(me.record) : dataSource.indexOf(me.record)) : -1;
            }
        }
        if (me.record !== oldRecord) {
            me.generation++;
        }
        return me;
    },
    
    setColumn: function(col) {
        var me = this,
            colMgr = me.view.getVisibleColumnManager(),
            oldColumn = me.column;
 
        // Maintainer: 
        // We MUST NOT update the context view with the column's view because this context 
        // may be for an Ext.locking.View which spans two grid views, and a column references 
        // its local grid view. 
        if (col !== undefined && col !== null) {
            if (typeof col === 'number') {
                me.colIdx = col;
                me.column = colMgr.getHeaderAtIndex(col);
            } else if (col.isHeader) {
                me.column = col;
                // Must use the Manager's indexOf because view may be a locking view 
                // And Column#getVisibleIndex returns the index of the column within its own header. 
                me.colIdx = colMgr.indexOf(col);
            }
        }
        if (me.column !== oldColumn) {
            me.generation++;
        }
        return me;
    }
});
