// Todo:
// 1. Only create section when user succesfully chooses the csv
// 2. Make attendance editable
// 3. Test using several sections
// 4, Email output


var db;


function createButtonsMainScreen() {
    $("#buttonSection").html("");
    $("#buttonSection").append('<ons-button onclick="addSection()">Add Course</ons-button><br>');
    $("#buttonSection").append('<ons-button onclick="readTables()">Read Tables</ons-button><br>');
    createSectionButtons();
}

function createSectionButtons () {
    // ons.notification.alert('lets createSectionButtons');
    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM sections", [], 
        function(tx, rs) {
            var row;
            for (var i = 0; i < rs.rows.length; i++) {
                row = rs.rows.item(i);
                $("#buttonSection").append('<ons-button onclick="showSection(\'' + row.name +  '\')">' + row.name +  '</ons-button><br>');
            }
        }, 
        function() { ons.notification.alert('error on createSectionButtons'); });
    });
}


function showSection(sectionID) {
    db.transaction(function (tx) {
        tx.executeSql(
            "SELECT studentSection.sectionID as secID, students.studentID as id, students.name as studName  FROM studentSection left join students on studentSection.studentID = students.studentID WHERE studentSection.sectionID=?", 
            [sectionID], 
            // function() { dbg("GOOOD SELECT students for show section ") }, 
            buildAttendanceSheet,
            function() { dbg('Error SELECTING from studentSection Table'); }
        );
    });

    //const navigator = document.querySelector('#navigator');
    //navigator.pushPage('attendanceSheet.html', 

    //     {animation: "slide", onTransitionEnd: function() {
    //         ons.notification.alert('transition edsss: ' + name);
    //     }
    // }
    //{data: {title: sectionID, students:[{id:11, name:"uno"},{id:12, name:"dos"}]}} 
    //);
    // ons.notification.alert('changing the toolbar? ' + name);
    // $('#toolBarTitle').html(name);
    // ons.compile($('#toolBarTitle')) ;
}


function buildAttendanceSheet(tx, rs) {
    currentSection = rs.rows.item(0).secID;
    dbg("In  buildAttendanceSheet");
    var row;
    var strOut = "";
    studArray = [];
    var sectionID = rs.rows.item(0).secID;

    for (var i = 0; i < rs.rows.length; i++) {
        row = rs.rows.item(i);
        if (row != undefined) {
            dbg("build attendance: " + row.id + " " + row.studName );
            studArray.push({id: row.id, name: row.studName})
        }
    }

    const navigator = document.querySelector('#navigator');
    navigator.pushPage('attendanceSheet.html', 
        {   data: {
                title: sectionID, 
                students:studArray 
            }
        } 
    );
}

var currentSection;

function getDate() {
    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
    var yyyy = today.getFullYear();

    today =  yyyy + '-' + mm + '-' + dd;
    return today;
}


function readCheckboxes () {
    var result = [];
    var ctr = 0;
    var strDate = getDate();
    $("#studentList input:checkbox").each(function(d) {
        dbg($(this).val() + " " + $(this).prop("checked"));

        addAttendance($(this).val(),strDate,$(this).prop("checked") ? 1 : 0);

        //alert($(this).val() + " " + $(this).prop("checked")); 
            //var str = $(this).val();
            // result.push({ name : $(this).val(), value: ($(this).prop("checked") ? 1 : 0)  });
            // app.addAttendance($(this).val(),getDate(),$(this).prop("checked") ? 1 : 0);
            // ctr = ctr + 1;
        });

        // alert(JSON.stringify(result));
        // alert("udpated " + ctr + "records");
}

function foo() { 
    
    $('#toolBarTitle').html(name); 
}

function addAttendance(id, date, status) {
    // dbg("Adding attendance for:" + currentSection + " " + id + " " + date + " " + status) ;
    db.transaction(function (tx) {
        // var ts = new Date().toUTCString();
        tx.executeSql(
            "INSERT INTO attendance(sectionID, studentID, date, status) VALUES (?,?,?,?)", 
            [currentSection, id, date, status],
            function() {dbg("Inserted to attendance: " + id + " " + status)}, 
            function() {dbg("ERROR Insering to attendance: " + id + " " + status)}
        );
    });
}

function doOpenDatabase() {
    var dbSize = 1 * 1024 * 1024; // 5MB
    // open database
    db = openDatabase("Todo", "", "Todo manager", dbSize, 
      function() {
        ons.notification.alert('db successfully opened or created');
      },
      function() { 
        ons.notification.alert('Error openning database');
      }
    );
}

function createStudentTable () {
    // ons.notification.alert('Creating student table');
    db.transaction(function (tx) {
        // tx.executeSql('DROP TABLE IF EXISTS students');
        // tx.executeSql('DROP TABLE IF EXISTS studentSection');
        // tx.executeSql('DROP TABLE IF EXISTS sections');
        // tx.executeSql('DROP TABLE IF EXISTS attendance');
        

        tx.executeSql("CREATE TABLE IF NOT EXISTS students(studentID TEXT NOT NULL, name TEXT, PRIMARY KEY (studentID))", [],
            function() { dbg("Created students table");}, 
            function() { dbg("Error creating students table") }
        );

        tx.executeSql("CREATE TABLE IF NOT EXISTS sections(sectionID TEXT PRIMARY KEY ASC, name TEXT)", [],  
            function() {dbg("Created sections table");},
            function() {dbg("Error creating sections table");}
        );
        
        tx.executeSql("CREATE TABLE IF NOT EXISTS studentSection(studentID TEXT NOT NULL, sectionID TEXT NOT NULL, primary key (studentID,sectionID))", [],
            function() { dbg("Created studentSection table"); }, 
            function() { dbg("Error studentSection table"); }
        );

        tx.executeSql('CREATE TABLE IF NOT EXISTS attendance (studentID TEXT not null, date DATE not null, sectionID TEXT NOT NULL, status TINYINT(1),  primary key (studentID,sectionID, date) )', [],
            function() { dbg("Created attendance table"); }, 
            function() { dbg("Error attendance table"); }
        );
    });
} 

function dbg(str) {
    if ( $('#txtDebug').length > 0) {
        $("#txtDebug").val($("#txtDebug").val() + str + "\n");
    }
}

function addStudent  (name, email) {
    // ons.notification.alert('addStudent ' + name + " " + id);
    db.transaction(function (tx) {
        tx.executeSql("INSERT INTO students(studentID, name) VALUES (?,?)", [email,name], 
        function(){}, 
        function(){ons.notification.alert('Error inserting a student');});
    });
}

function addStudentToSection  (email, section) {
    // ons.notification.alert('addStudent ' + name + " " + id);
    db.transaction(function (tx) {
        tx.executeSql("INSERT INTO studentSection(studentID, sectionID) VALUES (?,?)", [email,section], 
        function(){dbg("addStudentToSection: " + email.substring(0,10) + ":" + section);}, 
        function(){dbg('Error in addStudentToSection');});
    });
}

function insertSectionToDB  (name) {
    db.transaction(function (tx) {
        tx.executeSql("INSERT INTO sections(name) VALUES (?)", [name],
            function() { 
                dbg('Inserted the section ' + name);
                // createSectionButtons();
                createButtonsMainScreen();
            }, 
            function () {
                dbg('Error inserting the section ' + name);
            }
        );
    });
}

function addStudentConditional  (name, email, section) {
    // ons.notification.alert('adding conditionally ' + email.substring(0,10));
    db.transaction(function (tx) {
        tx.executeSql("SELECT studentID FROM students WHERE studentID=?", [email], 
            function (tx, rs ) { 
                if ( rs.rows.length == 0) {
                    $("#txtDebug").val($("#txtDebug").val() + 'adding: ' +  name.substring(0,10) + '\n');
                    // ons.notification.alert('rows: ' + rs.rows.length );
                    addStudent(name, email);
                    addStudentToSection(email,section);
                }
                else {
                    // ons.notification.alert('rows: ' + rs.rows.length );
                    addStudentToSection(email,section);
                }
            }, 
            function () {ons.notification.alert('error on SELECT COUNT'); }
        );
    });
}

function onSuccessCreateStudents (transaction, resultSet) {
    dbg("onSuccessCreateStudents");
}

function onErrorCreateStudents (transaction, resultSet) {
    dbg("onErrorCreateStudents");
}

function onSuccessCreate (transaction, resultSet) {
    console.log('Student RowsAffected: ' + resultSet.rowsAffected);
}
function onSuccess (transaction, resultSet) {
    console.log('RowsAffected: ' + resultSet.rowsAffected);
}
function onError (transaction, resultSet) {}

function CSVToArray( strData, strDelimiter ){
    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = (strDelimiter || ",");
    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp(
        (
            // Delimiters.
            "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
            // Quoted fields.
            "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
            // Standard fields.
            "([^\"\\" + strDelimiter + "\\r\\n]*))"
        ),
        "gi"
        );
    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [[]];
    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;
    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec( strData )){
        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[ 1 ];
        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (
            strMatchedDelimiter.length &&
            (strMatchedDelimiter != strDelimiter)
            ){
            // Since we have reached a new row of data,
            // add an empty row to our data array.
            arrData.push( [] );
        }
        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[ 2 ]){
            // We found a quoted value. When we capture
            // this value, unescape any double quotes.
            var strMatchedValue = arrMatches[ 2 ].replace(
                new RegExp( "\"\"", "g" ),
                "\""
                );
        } else {
            // We found a non-quoted value.
            var strMatchedValue = arrMatches[ 3 ];
        }
        // Now that we have our value string, let's add
        // it to the data array.
        arrData[ arrData.length - 1 ].push( strMatchedValue );
    }
    // Return the parsed data.
    return( arrData );
}

function getNameFields(A) {
    var result = Array();
    $.each(A, function( index, value ) {
      if (value.toUpperCase().indexOf("NAME") >= 0)
        result.push(index);
    });
    return result;
}

function addSection() {
    
    var dialog = document.getElementById('my-dialog');

    if (dialog) {
      dialog.show();
    } else {
      ons.createElement('dialog.html', { append: true })
        .then(function(dialog) {
          dialog.show();
        });
    }

}

function killDialog(id) {
    document
    .getElementById(id)
    .hide();
}

function hideDialog(id) {

    var sectionName = $("#sectionName").val();
    if (sectionName.length == 0) {
        $("#sectionDialogError").text("Name can't be blank");
        return;
    }

    // ons.notification.alert("lets check section: " + sectionName);
    db.transaction(function (tx) {
        tx.executeSql("SELECT sectionID  FROM sections WHERE name=?", [sectionName], 
            function (tx, rs ) { 
                
                // ons.notification.alert("counting section: " + sectionName);
                if ( rs.rows.length == 0) {
                    // ons.notification.alert('i will create the section '+ sectionName);
                    insertSectionToDB(sectionName);
                    chooseFile(sectionName);
                    // now hide the dialog
                    document
                    .getElementById(id)
                    .hide();
                }
                else {
                    $("#sectionDialogError").text(sectionName + " already exists!");                    
                }
            }, 
            function () {ons.notification.alert("an error on select count secton"); }
        ); 
    });   

    // determine if courseExists

    // ons.notification.alert("value is " + $("#sectionName").val());
    

  }

function readTables () {
    // ons.notification.alert('lets read tables');
    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM students", [], dbgOut, 
        function() { ons.notification.alert('error on read tables'); });
    });
    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM studentSection", [], dbgOutSections, 
        function() { dbg('Error SELECTING from studentSection Table'); });
    });
    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM attendance", [], dbgOutAttendance, 
        function() { dbg('Error SELECTING from attendance Table'); });
    });



}
function dbgOut(tx, rs) {
        var row;
        var strOut = "";
        // ons.notification.alert('dbgOut ' + rs.rows.length);
        for (var i = 0; i < rs.rows.length; i++) {
            row = rs.rows.item(i);
            
            if (row != undefined) {
                strOut = strOut + " " + row.studentID.substring(0,10) + ":" + row.name.substring(0,10)  + "\n";
            }

        }
        
        
        // $("#dbg").text(strOut);
        $("#txtDebug").val(strOut);
        // ons.notification.alert(strOut);
    
}

function dbgOutSections(tx, rs) {
    var row;
    var strOut = "";
    for (var i = 0; i < rs.rows.length; i++) {
        row = rs.rows.item(i);
        
        if (row != undefined) {
            strOut = strOut + " " + row.studentID.substring(0,10) + ":" + row.sectionID + "\n";
        }

    }
    
    $("#txtDebug").val("Content of studentSection table\n" + strOut);
}

function dbgOutAttendance(tx, rs) {
    var row;
    var strOut = "";
    for (var i = 0; i < rs.rows.length; i++) {
        row = rs.rows.item(i);
        
        if (row != undefined) {
            strOut = strOut  + row.studentID + "," + row.sectionID + "," +  row.date +  "," + row.status + "\n";
        }

    }

    cordova.plugins.email.open({
        to:      'rafael.arce@upr.edu',
        subject: 'Attendance : ' + getDate(),
        body:    '<pre>' + strOut + '</pre>',
        isHtml:  true
    });
    
    $("#txtDebug").val("Content of attendance table\n" + strOut);
}


function chooseFile(section) {
    fileChooser.open(
        function(uri) {
            // alert(uri);
            window.resolveLocalFileSystemURL(uri /*cordova.file.externalApplicationStorageDirectory*/, function(dir) {
                // ons.notification.alert("got this name: " + dir.name +  " fullPath: " + dir.fullPath + "  toUrl:" + dir.toURL());
                dir.file(function (file) {
                    var reader = new FileReader();
                    
                    reader.onloadend = function() {
                        var studArray = CSVToArray(this.result,",");
                        var nameFields = getNameFields(studArray[0]);
                        var strAllStudents = "";
                        for (var i = 1; i < studArray.length; i=i+1) {
                            var fullName  = "";
                            for (var j = 0; j < nameFields.length; j=j+1) {
                                fullName = fullName + studArray[i][nameFields[j]] + " ";
                            }
                            if (fullName.toUpperCase().indexOf("UNDEFINED") < 0) {
                                addStudentConditional(fullName, studArray[i][5],section);
                                strAllStudents = strAllStudents + fullName;
                                // ons.notification.alert(fullName);
                            }
                        }
                        // app.createSheet();
                        //ons.notification.alert(strAllStudents);
                    };
            
                    reader.readAsText(file);
            
                }, function() {alert("onErrorReadFile");});


            });

        }, 
        function() {}
        );
}