var db

function initDatabase()
{
    if(db == null)
    {
        db = openDatabaseSync("RenRenAccountDB", "1.0", "RenRen QML SQL", 1000000);
        console.log("Create RenRenAccountDB...");
    }

    db.transaction(
        function(tx)
        {
            tx.executeSql('CREATE TABLE IF NOT EXISTS RenRenAccount(user_id TEXT, user_name TEXT, passwd TEXT)');
        }
    )
}

function clearDatabase()
{
    if(db == null)
    {
        db = openDatabaseSync("RenRenAccountDB", "1.0", "RenRen QML SQL", 1000000);
    }
    db.transaction(
        function(tx)
        {
            tx.executeSql('DROP TABLE IF EXISTS RenRenAccount');
        }
     )
}

function loadConsumer(consumer)
{
    initDatabase();
    var ret = false;

    db.transaction(
        function(tx)
        {
            var rs = tx.executeSql('SELECT * FROM RenRenAccount where user_id="' + consumer.user_id + '"');
            console.log("SELECT Result: " + rs.rows.length);
            if(rs.rows.length > 0)
            {
                for(var i = 0; i < rs.rows.length; i++)
                {
                    consumer.user_id = rs.rows.item(i).user_id;
                    consumer.user_name = rs.rows.item(i).user_name;
                    consumer.passwd = rs.rows.item(i).passwd;

                    console.log("user_name:" + rs.rows.item(i).user_name);
                    console.log("passwd:" + rs.rows.item(i).passwd);
                    ret = true;
                    break;
                }
            }
        }
    );

    return ret;
}

function createConsumer(consumer)
{
    initDatabase();
    if(consumer.user_name.length == 0)
    {
        return false;
    }

    db.transaction(
        function(tx)
        {
            var rs = tx.executeSql('SELECT * FROM RenRenAccount where user_name="' + consumer.user_id + '"');
            if(rs.rows.length > 0)
            {
                //update
            }
            else
            {
                tx.executeSql('INSERT INTO RenRenAccount VALUES(?, ?, ?)', [ consumer.user_id,consumer.user_name, consumer.passwd]);
            }
        }
    )
}



