// Student Dorm Tab: Functions ------------------------------------------------

// -------------------------------------------------------------
// grid data store {"id":"North","editid":"North","type":"COED","capacity":"2001","students":"6"}
var dormDataArr = new Ext.data.Store({
    url: '/mvc6c/dormGetAll',
    reader: new Ext.data.JsonReader({
        root:'theArray',
        id:'id'
    }, [
    'id',
    'editid',
    'type',
    'capacity',
    'students'
    ])
});
dormDataArr.load();
var rowDorm = Ext.data.Record.create([
    'id',
    'name'
    ]);
// Student Dorm Grid ------------------------------------------------
var editorDorm = new Ext.form.TextField({
    allowBlank: false,
    maxLength: 100
});
var editorDormType = new Ext.form.TextField({
    allowBlank: false,
    maxLength: 100
});
var editorDormCapacity = new Ext.form.TextField({
    allowBlank: false,
    maxLength: 100
});
var dormGrid = new Ext.FormPanel({
    title: 'POD List',
    height: 300,        // higher than the grid height
    width : 880,        // hard code for MS IE browser
    activeTab: 0,
    frame: true,
    items: [{
        xtype: 'editorgrid',
        store: dormDataArr,
        id: 'gridDorms',
        height: 260,
        clicksToEdit: 1,
        stripeRows: true,
        selModel: new Ext.grid.RowSelectionModel(),
        columns: [
        {
            header: "POD",
            dataIndex: 'id',
            sortable: true,
            width: 100
        },
        {
            header: "POD Edit ID",
            dataIndex: 'editid',
            sortable: true,
            editor: editorDorm
        },
        {
            header: "Location",
            dataIndex: 'type',
            sortable: true,
            editor: editorDormType
        },
        {
            header: "Capacity",
            dataIndex: 'capacity',
            sortable: true,
            editor: editorDormCapacity
        },
        {
            header: "No. of Job",
            dataIndex: 'students',
            sortable: true,
            width: 100
        }
        ]
    }]
});

// Menu Functions --------------------------------------------------------------

function doRetriveDorms(){
    dh.overwrite( 'theMsgtext0', 'Menu: Refresh, Retrieve: List POD data' );
    dormDataArr.load();
}

function doCreateDorm(){
    dh.overwrite( 'theMsgtext0', 'Menu: Create POD' );
    var grid = Ext.ComponentMgr.get('gridDorms');
    grid.getStore().insert(
        0,  // Insert new record on first line
        new rowDorm({
            id: '0',    // default values
            capacity: '100'
        })
        );
    grid.startEditing(0,1); // row, column}
}

function doDeleteDorm(){
    dh.overwrite( 'theMsgtext0', 'Menu: Delete POD' );
    var grid = Ext.ComponentMgr.get('gridDorms');  // Get the id of the EditorGridPanel
    var sm = grid.getSelectionModel();
    var theSelected = sm.getSelected();
    if (!sm.hasSelection()){
        Ext.Msg.show({
            title: 'No row Selected.',
            icon: Ext.MessageBox.INFO,
            buttons: Ext.MessageBox.OK,
            msg: 'Select a row from the grid to be Deleted.',
            width: 325
        });
        dh.overwrite( 'theMsgtext0', 'No row Selected.' );
        return;
    }
    dh.overwrite( 'theMsgtext0', 'Delete: '+theSelected.data.id );
    Ext.Msg.show({
        title: 'Delete',
        icon: Ext.MessageBox.QUESTION,
        buttons: Ext.MessageBox.YESNO,
        msg: 'Confirm Delete: '+theSelected.data.id+'?',
        fn: function(btn){
            if (btn == 'yes'){
                dormDelete(theSelected);
                grid.getStore().remove(theSelected);
                dh.overwrite( 'theMsgtext0', 'Menu: Deleted POD' );
            }
        }
    });
}

function doUpdateDorms(){
    dh.overwrite( 'theMsgtext0', 'Menu: Update: Save New and Edits' );
    var aGrid = Ext.ComponentMgr.get('gridDorms');
    var counter = 0;
    Ext.each( aGrid.getStore().getModifiedRecords(), function(record){
        counter++;
        alert("doUpdatePOD: counter = "+counter+": "+record.data.id+", "+record.data.type);
        if (record.data.id=="0") {
            dormInsert(record);
        }
        else {
            dormUpdate(record);
        }
    } );
    if (counter>0){
        aGrid.getStore().commitChanges();   // commit grid updates
        dormDataArr.load();                // re-load the grid
    }
    dh.overwrite( 'theMsgtext0', 'Menu: Update: Save New and Edits, number of updates = '+counter );
}

// Database Functions --------------------------------------------------------------

function dormInsert(record){
    alert('POD, POD Insert: '+record.data.editid);
    var conn = new Ext.data.Connection();
    conn.request({
        // http://localhost:8080/mvc6c/dormAdd?name=Math1
        url: '/mvc6c/dormAdd',
        // url: 'sampleData/success.json',
        params: {
            dormId: record.data.editid,
            dormType:record.data.type,
            dormCapacity:record.data.capacity
        },
        success: function(resp,opt) {
            dh.overwrite( 'theMsgtext1', 'POD Insert, success: '+record.data.editid+", "+record.data.type );
        // dormDataArr.load();
        },
        failure: function(resp,opt) {
            dh.overwrite( 'theMsgtext1', 'POD Insert: failure' );
        }
    });
}

function dormUpdate(record){
    alert('POD, POD Update: '+record.data.id);
    var conn = new Ext.data.Connection();
    conn.request({
        // url: 'sampleData/success.json',
        url: '/mvc6c/dormEdit',
        // http://localhost:8080/mvc6c/dormEdit?id=702&name=Math12
        params: {
            updateId: record.data.id,
            dormType: record.data.type,
            dormCapacity: record.data.capacity
        },
        success: function(resp,opt) {
            dh.overwrite( 'theMsgtext1', 'POD Updated: '+record.data.id );
        },
        failure: function(resp,opt) {
            dh.overwrite( 'theMsgtext1', 'POD Updated: failure' );
        }
    });
}

function dormDelete(record){
    alert('POD, POD Update: '+record.data.id);
    var conn = new Ext.data.Connection();
    conn.request({
        // http://localhost:8080/mvc6c/dormAdd?name=Math
        // http://localhost:8080/mvc6c/dormDelete?delId=1104
        url: '/mvc6c/dormDelete',
        // url: 'sampleData/success.json',
        params: {
            delId: record.data.id
        },
        success: function(resp,opt) {
            dh.overwrite( 'theMsgtext1', 'Delete: '+record.data.id+", "+record.data.type );
        },
        failure: function(resp,opt) {
            Ext.Msg.alert('Error', '*** Delete failed, could be someone else has already deleted it. Data has been refreshed.');
        }
    });
}

// eof
