var EVENTS = EVENTS || {};

EVENTS.table = {
    single : 'xm24_events_single',
    //repeat : 'xm24_events_repeat',
};

EVENTS.dateFormat = {
    store : {        
        date: "YYYY-MM-DD",
        hour: "HH:mm"
    },
    display : {
        date: "DD-MM-YYYY",
        hour: "HH:mm"
    }
};

EVENTS.storeDateFormat = EVENTS.dateFormat.store.date + " " + EVENTS.dateFormat.store.hour;
EVENTS.displayDateFormat = EVENTS.dateFormat.display.date + " " + EVENTS.dateFormat.display.hour;

EVENTS.formatDate = function(date, format) {
    var mdate = moment(date);
    
    return mdate.isValid() ? mdate.format(format) : "";
};

EVENTS.render = function() {
    var ret = checkConnection('ERR_EVENT');
    if (ret) {
        EVENTS.getDataAndLoad(ai1ec.cats.single);
        //EVENTS.getDataAndLoad(ai1ec.cats.repeat);
    } else {
        EVENTS.loadFromDb('#mostralista-'+ ai1ec.cats.single, ai1ec.cats.single);
        //EVENTS.loadFromDb('#mostralista-'+ ai1ec.cats.repeat, ai1ec.cats.repeat);
    }
};

EVENTS.getDataAndLoad = function (type) {
    type = type || ai1ec.cats.single;
    var table = type == ai1ec.cats.repeat ? 'xm24_events_repeat' : 'xm24_events_single';

    ai1ec.remote.getLastEvents(type, function(events) {
        var n_evs = events.length, 
            n_evs_ins = 0,
            n_evs_err = 0;

        if(n_evs > 0) {
            FONTE.dbHandler.executeSql('DELETE FROM ' + table , [], function() {
                for (var i = 0; i < events.length; i++) {
                    var event = events[i];
                    var evId = ai1ec.event.getId(event);
                    var evTitle = ai1ec.event.getTitle(event);
                    var evDesc = ai1ec.event.getDescription(event);
                    var evUrl = ai1ec.event.getUrl(event);
                    var evGeo = ai1ec.event.getGeo(event);
					var evImg = ai1ec.event.getImage(event);
                    
                    var evInitDate = EVENTS.formatDate(ai1ec.event.getInitDate(event), EVENTS.storeDateFormat);
                    var evEndDate = EVENTS.formatDate(ai1ec.event.getEndDate(event), EVENTS.storeDateFormat);
                    
                    FONTE.dbHandler.executeSql('INSERT INTO ' + table + ' VALUES (?,?,?,?,?,?,?,?)', [evId, evTitle, evDesc, evInitDate, evEndDate, evUrl, evGeo, evImg], 
                    //onSuccess
                    function (resultSet) {
                        n_evs_ins++;
                        console.log('resultSet.insertId: ' + resultSet.insertId);
                        console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
                        if(n_evs_ins + n_evs_err == n_evs - 1) {
                            if(n_evs_ins > 0) {
                                EVENTS.loadFromDb('#mostralista-'+ type, type);
                            }
                        }
                    }, 
                    //onError
                    function (error) {
                        n_evs_err++;
                        if(n_evs_ins + n_evs_err == n_evs - 1) {
                            if(n_evs_ins > 0) {
                                EVENTS.loadFromDb('#mostralista-'+ type, type);
                            } else {
                                EVENTS.errorHandler("Non ci sono nuovi eventi.", "info");
                            }
                        }
                        console.error("EVENTS.query() : ", error);
                    });
                }
            }, function(error){
                EVENTS.errorHandler("Err: errore nel TRUNCATE della tabella degli eventi");
            });
        } else {
            EVENTS.errorHandler("Non ci sono nuovi eventi.", "info");
        }
    });
};

EVENTS.hideLoader = function(){
    $.mobile.loading('hide');
};

EVENTS.errorHandler = function(msg, type) {
    if(type === 'info') {
        toastr.info(msg);
    } else {
        toastr.error(msg);
    }
    
    EVENTS.hideLoader();
};

EVENTS.loadFromDb = function (containerId, type) {
    var table = type == ai1ec.cats.repeat ? 'xm24_events_repeat' : 'xm24_events_single';
    FONTE.dbHandler.executeSql("SELECT * FROM " + table + " ORDER BY initDate COLLATE NOCASE ASC;", [], function (resultSet) {
         var items = [];
         for (var i = 0; i < resultSet.rows.length; i++) {
            var item = resultSet.rows.item(i);
            
            var evInitDate = EVENTS.formatDate(item.initDate, EVENTS.displayDateFormat);
            var evEndDate = EVENTS.formatDate(item.endDate, EVENTS.displayDateFormat);
            
            var evFrom = "<small>Da: " + evInitDate + "</small>";
            var evTo = " ";
            if(evEndDate !== "") {
                evTo += "<small>A: " + evEndDate + "</small>";
            }
            
            var li = "<li>" +
                        //"<img src='./image/virgolette_1.png' class='epuntato'/>" +
                        "<a class='event-"+type+"' href='#event' data-post='" + item.id + "' >" +
                            item.title + 
                        "</a>" +
                        "<br/>" +
                        evFrom + evTo +
                        "<hr class='post-divider'>"+
                     "</li>";
                    
            items.push(li);
        }
        
        $(containerId).empty();
        $("<ul/>", {
            html: items.join("")
        }).prependTo(containerId);

        EVENTS.hideLoader();
    }, function (error) {
        EVENTS.errorHandler("Err: nel caricamento dei dati dal db");
    });
};
