/*
Copyright (c) 2010, Greg Murray
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
   This product includes software developed by Greg Murray.
4. Neither the name of Greg Murray nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Greg Murray ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Greg Murray BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

window.pictureDao = function() {

    var db = null;
    var dataId = 1;
    var sql = {
      CREATE : "CREATE TABLE paintings (id REAL UNIQUE, json TEXT )",
      INSERT : "INSERT INTO paintings (id, json ) VALUES ( ?, ?)",
      UPDATE : "UPDATE paintings SET json = ? WHERE id = ?",
      GET : "SELECT json FROM paintings",
      COUNT : "SELECT COUNT(*) FROM paintings"
    };

    function initDB( _callback ) {
        try {
            if ( window.openDatabase ) {
                db = openDatabase("Storage", "1.0", "Painting Database", 100000 );
                checkIfDBInitialized();
                if ( !db ) {
                    alert( "Failed to open the database. Have you allocated enough space?" );
                } else {
                    if ( typeof _callback === "function" ) {
                        _callback.apply({}, []);
                    }
                }
            }
        } catch( error ) { 
            alert( "Error trying to open database " + error );
        }
    }

    function checkIfDBInitialized() {
        db.transaction( 
               function(tx) {
                tx.executeSql( sql.COUNT, [],
                            function(tx, result) {
                                // do nothing 
                            },
                            function( tx, error) {
                               tx.executeSql( sql.CREATE, [],
                                              function(result) {
                                   // create our single row
                                   tx.executeSql( sql.INSERT, [ dataId, "[]" ]);
                             });
            });
        });
    }

    function load( _callback) {
        db.transaction(function(tx) {
            tx.executeSql( sql.GET, [], function(tx, result) {
                if (result.rows.length > 0) {
                    var _row = result.rows.item(0);
                    var _json = _row['json'];
                    if ( typeof _callback === "function" ) {
                        _callback.apply( {}, [ _json ] );
                    }
                }
            }, function(tx, error) {
                alert( "Failed to retrieve paintings from database : " + error.message );
                return;
            });
        });
    };

    function save( _json, _callback ) {
        db.transaction(function (tx) {
            tx.executeSql( sql.UPDATE, [ _json, dataId ], _callback);
        });
    };

    return {
        init : initDB,
        load : load,
        save : save
    };
}();
