/**
 * @version 0.0.2
 * @since 0.0.1
 * @author Shaun Chyxion <br />
 * chyxion@163.com
 * Dec 05, 2014 11:39:58
 */
Ext.define ('Tigon.views.CodeGen', {
    extend: 'Ext.container.Container',
    title: 'Tigon Code Gen',
    layout: 'border',
    items: [{
    	xtype: 'container',
        region: 'west',
        split: true,
        layout: 'border',
        width: 186,
        defaults: {
            xtype: 'treepanel'
        },
        items: [{
            title: 'Items Generated',
            split: true,
            height: 286,
            region: 'north',
            tbar: [{
                text: 'Remove Model',
                name: 'btn_remove',
                disabled: true,
                iconCls: 'remove',
                handler: function () {
                    var t = this.up('treepanel');
                    Ext.MessageBox.show({
                        title: 'Are you sure?',
                        msg: 'Are you sure to remove model(s) selected without drop tables?',
                        buttons: Ext.MessageBox.YESNOCANCEL,
                        fn: function(btn) {
                            if (btn != 'cancel') {
                                var items = [];
                                Ext.Array.each(t.getView().getChecked(), function(rec) {
                                    items.push({
                                        module: rec.get('module'),
                                        model: rec.get('model')
                                    });
                                });
                                if (!items.length) {
                                    var rec = t.getSelectionModel().getLastSelected();
                                    items.push({
                                        module: rec.get('module'),
                                        model: rec.get('model')
                                    });
                                }
                                Ajax.del('codegen', {
                                    items: items,
                                    dropTable: btn == 'no'
                                }, function() {
                                    t.getStore().reload();
                                    // right container
                                    var rc = t.up().next('container'),
                                        form = rc.down('form');
                                    form.getForm().reset();
                                    form.down('grid').getStore().removeAll();
                                    // remove demo grid
                                    // rc.down('container[name=demo_grid]').removeAll();
                                    Message.alert('Remove Success.');
                                });
                            }
                        },
                        icon: Ext.MessageBox.QUESTION
                    });
                }
            }],
            store: Store.tree({
                url: 'codegen/list',
                fields: ['text', 'name', 'module', 'model', 'cols', 'table'],
                root_text: 'Models'
            }),
            listeners: {
                select: function(rm, rec) {
                    this.down('toolbar')
                        .down('button[name=btn_remove]')
                        .setDisabled(!rec.isLeaf());
                    if (rec.isLeaf()) {
                        // right container
                        var rc = this.up().next('container'),
                            form = rc.down('form');
                        form.getForm().setValues(rec.getData());
                        form.down('grid').getStore().loadData(rec.get('cols'));
                    }
                }
            }
        }, {
            title: 'Tables',
            split: true,
            region: 'center',
            tbar: [{
                text: 'Reload',
                iconCls: 'refresh',
                handler: function () {
                    this.up('treepanel').getStore().reload();
                }
            }],
            store: Store.tree({
                url: 'codegen/tables',
                fields: ['id', 'text', 'module', 'model', 'cols', 'table'],
                root_text: 'Tables'
            }),
            listeners: {
                select: function(rm, rec) {
                    if (rec.isLeaf()) {
                        // right container
                        var form = this.up().next('form');
                        form.getForm().setValues(Ext.merge(rec.getData(), {
                            createTable: false
                        }));
                        form.down('grid').getStore().loadData(rec.get('cols'));
                    }
                }
            }
        }]
    }, {
        xtype: 'form',
        region: 'center',
        split: true,
        height: 312,
        autoScroll: true,
        bodyPadding: 12,
        layout: 'vbox',
        defaults: {
            width: '96%',
            labelWidth: 86
        },
        tbar: [{
            text: 'New model',
            iconCls: 'add',
            handler: function(btn) {
                var form = btn.up('form'),
                    s = form.down('grid').getStore();
                    s.removeAll();
                    s.add({
                        name: 'id',
                        javaType: 'String',
                        col: 'id',
                        sqlType: 'varchar(36)'
                    }, {
                        name: 'dateCreated',
                        javaType: 'Date',
                        col: 'date_created',
                        sqlType: 'datetime'
                    }, {
                        name: 'dateUpdated',
                        javaType: 'Date',
                        col: 'date_updated',
                        sqlType: 'datetime'
                    });
            }
        }, {
            text: 'Generate!',
            iconCls: 'save',
            handler: function(btn) {
                var form = btn.up('form');
                if (form.isValid()) {
                    var s = form.down('grid').getStore();
                    if (s.getCount()) {
                        var params = form.getForm().getValues(),
                            columns = [];
                        s.each(function(rec) {
                            columns.push(rec.getData());
                        });
                        params.columns = columns;
                        Dialog.confirm(s.collect('isKey').length > 1 ?
                                'Are you sure to submit?' :
                                'No primary key, are you sure to submit?', function() {
                            Ajax.post('codegen', params, function() {
                                form.previousNode('treepanel')
                                    .previousNode('treepanel')
                                    .getStore()
                                    .reload();
                                Message.alert('Generate successfully.');
                            });
                        });
                    }
                    else {
                        Message.warn('No Columns.');
                    }
                }
            }
        }],
        items: [{
            xtype: 'box',
            html: [
                '<span style="color: #333;">Note: </span>',
                'Welcome.'
            ].join(''),
            padding: '0 0 12 0',
            style: {
                fontSize: '12pt',
                color: '#00F'
            },
        }, {
            fieldLabel: 'Options',
            xtype: 'checkboxgroup',
            defaults: {
                checked: false,
                xtype: 'checkbox',
                inputValue: true
            },
            columns: 3,
            items: [{
                boxLabel: 'Gen controller',
                checked: components.indexOf('controller') > -1,
                name: 'genController'
            }, {
                boxLabel: 'Gen service',
                name: 'genService'
            }, {
                boxLabel: 'Gen mapper',
                checked: components.indexOf('mapper') > -1,
                name: 'genMapper'
            }, {
                boxLabel: 'Gen model',
                checked: components.indexOf('model') > -1,
                name: 'genModel'
            }, {
                boxLabel: 'Gen form',
                checked: components.indexOf('form') > -1,
                name: 'genView'
            }]
        }, {
            xtype: 'fieldcontainer',
            fieldLabel: 'Columns',
            items: {
                xtype: 'grid',
                minHeight: 128,
                plugins: [Ext.create('Ext.grid.plugin.CellEditing', {
                    clicksToEdit: 1
                })],
                store: {
                    store: 'json',
                    fields: ['name', 'javaType', 'col', 'sqlType',
                        {name: 'notNull', type: 'boolean', defaultValue: true},
                        {name: 'isKey', type: 'boolean', defaultValue: false},
                        {name: 'isIndex', type: 'boolean', defaultValue: false}]
                },
                columns: [{
                    xtype: 'rownumberer'
                }, {
                    dataIndex: 'name',
                    text: 'Property name',
                    width: 128,
                    editor: {
                        xtype: 'textfield',
                        allowBlank: false,
                        listeners: {
                            change: function(t, nv, ov) {
                                t.up().up()
                                .getSelectionModel()
                                .getLastSelected()
                                .set('col',
                                    nv.split(/(?=[A-Z])(?=[A-Z][a-z])|(?=[^A-Z])(?=[A-Z])|(?=[^a-zA-Z])(?=[a-z])|(?=[A-Za-z])(?=[^A-Za-z])/)
                                    .join('_').
                                    toLowerCase());
                            }
                        }
                    }
                }, {
                    dataIndex: 'javaType',
                    text: 'Java Type',
                    flex: 1,
                    editor: {
                        xtype: 'combo',
                        typeAhead: true,
                        editable: false,
                        triggerAction: 'all',
                        store: [
                            ['String', 'String'],
                            ['int', 'int'],
                            ['Integer', 'Integer'],
                            ['long', 'long'],
                            ['Long', 'Long'],
                            ['double', 'double'],
                            ['Double', 'Double'],
                            ['Date', 'Date'],
                            ['boolean', 'boolean'],
                            ['Boolean', 'Boolean'],
                            ['byte', 'byte'],
                            ['Byte', 'Byte'],
                            ['byte[]', 'byte[]'],
                            ['Byte[]', 'Byte[]']
                        ]
                    }
                }, {
                    dataIndex: 'col',
                    text: 'Column name',
                    width: 128,
                    editor: {
                        xtype: 'textfield'
                    }
                }, {
                    dataIndex: 'sqlType',
                    text: 'SQL type',
                    flex: 1,
                    editor: {
                        allowBlank: false,
                        xtype: 'combo',
                        typeAhead: true,
                        editable: true,
                        triggerAction: 'all',
                        store: [
                            ['date', 'date'],
                            ['datetime', 'datetime'],
                            ['char(36)', 'char(36)'],
                            ['varchar(36)', 'varchar(36)'],
                            ['bit', 'bit'],
                            ['bigint', 'bigint'],
                            ['int', 'int'],
                            ['float', 'float']
                        ]
                    }
                }, {
                    dataIndex: 'notNull',
                    text: 'Not Null',
                    width: 76,
                    renderer: function(v) {
                        return v || '';
                    },
                    editor: {
                        xtype: 'checkbox',
                        inputValue: true
                    }
                }, {
                    dataIndex: 'isKey',
                    text: 'Primary key',
                    width: 76,
                    renderer: function(v) {
                        return v || '';
                    },
                    editor: {
                        xtype: 'checkbox',
                        inputValue: true
                    }
                }],
                tbar: [{
                    text: 'Add column',
                    iconCls: 'add',
                    handler: function () {
                        var s = this.up('grid').getStore(),
                            name = 0;
                            Ext.each(s.collect('name'), function(col) {
                                var m = col.match(/^name(\d*)$/);
                                if (m) {
                                    var num = parseInt(m[1]);
                                    if (isNaN(num)) {
                                        name = 1;
                                    }
                                    else if (num + 1 > name) {
                                        name = num + 1;
                                    }
                                }
                            });
                        name = 'name' + (name ? name : '');
                        s.add({
                            name: name,
                            javaType: 'String',
                            col: name,
                            sqlType: 'varchar(36)',
                            notNull: true,
                            isKey: false
                        });
                    }
                }, {
                    text: 'Remove column',
                    iconCls: 'remove',
                    handler: function (btn) {
                        var g = btn.up('grid'),
                            ss = g.getSelectionModel().getSelection();
                        if (ss.length) {
                            Dialog.confirm(
                                'Are you sure to remove the column selected?',
                                function() {
                                    g.getStore().remove(ss);
                            });
                        }
                        else {
                            Message.warn('Please Select Column To Remove.');
                        }
                    }
                }]
            }
        }, {
            xtype: 'textfield',
            name: 'pkg',
            fieldLabel: 'Base package',
            allowBlank: true,
            emptyText: 'Default base package (' + pkg + ').'
        }, {
            xtype: 'textfield',
            name: 'module',
            fieldLabel: 'Module',
            emptyText: 'Subpackage of base package.'
        }, {
            xtype: 'textfield',
            name: 'model',
            fieldLabel: 'Model name',
            value: 'ModelName',
            allowBlank: false
        }, {
            xtype: 'textfield',
            name: 'table',
            fieldLabel: 'Table name',
            allowBlank: false
        }]
    }]
});
