﻿define(['file', 'pouch-fruidown', 'pouch-localstorage', 'pouch-search', 'pouch-stream'], function (File) {

    var dbs = [];
    var findDB = function (name) {
        for (var idx = 0; idx < dbs.length; idx++) {
            if (dbs[idx].Name == name) {
                return dbs[idx].DB;
            };
        }

        return null;
    };

    var openDB = function (name) {
        var db = findDB(name);
        if (db != null) return db;

        try{
            db = new PouchDB(name + 'DB', { adapter: 'websql' });
            console.log('pouchdb with websql is create: ' + db._adapter + '  ' + db.adapter)
        } catch (err) {
            console.log(err);
        }

        if (db.adapter == undefined || db.adapter == null) {
            try {
                db = new PouchDB(name + 'DB');
                console.log('pouchdb is create. Adapter = ' + db.adapter)
            } catch (err) {
                console.log(err);
            }
        };

        if (db.adapter == undefined || db.adapter == null) {
            try{
                db = new PouchDB(name + 'DB', { adapter: 'localstorage' });
                console.log('pouchdb with localstorage is create')
            } catch (err) {
                console.log(err);
            }
        };

        if (db.adapter == undefined || db.adapter == null) {
            try {
                db = new PouchDB(name + 'DB', { adapter: 'fruitdown' });
                console.log('pouchdb with fruitdown is create')
            } catch (err) {
                console.log(err);
            }
        };

        if (db.adapter == undefined || db.adapter == null) {
            console.log('failed to open pouchDB!');
            return null;
        } else {
            dbs.push({ Name: name, DB: db })
            return db;
        }
    };

    var removeDB = function (name) {
        dbs = jQuery.grep(dbs, function (db) {
            return db.Name != name;
        });
    };

    var destroyDB = function (name, callback) {
        var db = openDB(name)
        if (db != null) {
            db.destroy().then(function (response) {
                console.log('DB ' + name + ' is destroied!')
                removeDB(name);
                callback(true)
            }).catch(function (err) {
                console.log(err);
                callback(false);
            });
        };
    };

    var addGuaHist = function (guatime, ben, bian, type, titel) {
        var db = findDB('gua');
        db.put({
            _id: new Date(Date.now()),
            guatime: guatime,
            bengua: ben,
            biangua: bian,
            type: type,
            titel: titel,
        }).then(function (response) {
            // handle response
            console.log('successed add gua history')
        }).catch(function (err) {
            console.log(err);
        });
    };

    var addBaziHist = function (birthday, name, city, sex, realtime) {
        var db = findDB('bazi');
        db.put({
            _id: new Date(Date.now()),
            birthday: birthday,
            name: name,
            city: city,
            sex: sex,
            realtime: realtime,
        }).then(function (response) {
            // handle response
            console.log('successed add bazi history')
        }).catch(function (err) {
            console.log(err);
        });
    };

    var fetchHistories = function (skip, table, callback) {
        var db = findDB(table);

        db.allDocs({
            include_docs: true,
            skip: skip,
            limit: 100,
            descending: true
        }).then(function (result) {
            callback(result.rows);
        }).catch(function (err) {
            console.log(err)
            callback(null);
        });
    };

    var removeDoc = function (docId, docRev, table) {
        var db = findDB(table);
        if (db != null) {
            db.remove(docId, docRev).then(function () {
                console.log('doc ' + docId + ' wurde geloescht')
            }).catch(function (err) {
                console.log('delete doc err : ' + err)
            });
        } else {
            console.log('doc nicht gefunden')
        };
    };

    var fetchDBInfo = function (table, callback) {
        var db = findDB(table);
        db.info().then(function (result) {
            // handle result
            // console.log(result)
            callback(result.doc_count);
        }).catch(function (err) {
            console.log(err);
            callback(0)
        });
    };

    return {
        OpenDB: function (name) {
            return openDB(name) != null;
        },

        AddGuaHist: function (guatime, ben, bian, type, titel) {
            if (openDB('gua') != null) {
                addGuaHist(guatime, ben, bian, type, titel);
            };
        },

        AddBaziHist: function (birthday, name, city, sex, realtime) {
            if (openDB('bazi') != null) {
                addBaziHist(birthday, name, city, sex, realtime);
            };
        },

        FetchHistories: function (skip, table, callback) {
            if (openDB(table) != null) {
                fetchHistories(skip, table, callback);
            };
        },

        GetHisDBInfos: function (name, callback) {
            if (openDB(name) != null) {
                fetchDBInfo(name, callback);
            };
        },

        ExportDB: function (name) {
            var db = findDB(name);

            var MemoryStream = window.memorystream;
            var stream = new MemoryStream();

            var dumpedString = '';
            stream.on('data', function (chunk) {
                dumpedString += chunk.toString();
            });

            db.dump(stream).then(function () {
                console.log('dump erfolg')
                console.log(stream)
                File.SaveString2Disk(dumpedString, name);
            }).catch(function (err) {
                console.log('dump error: ', err);
            });

        },

        ImportDB: function (data, table) {
            //destroyDB(table, function (erfolg) {
            //    if (erfolg == false) {
            //        console.log('can not destroy DB')
            //        return;
            //    }

            //    var MemoryStream = window.memorystream;
            //    var stream = MemoryStream.createReadStream(data);

            //    var db = openDB(table);
            //    if (db == null) {
            //        console.log('can not open db')
            //        return;
            //    } 

            //    db.load(stream).then(function (res) {
            //        console.log('load erfolg: ')
            //        alert('成功导入数据库！')
            //    }).catch(function (err) {
            //        console.log('load error: ', err);
            //    });
            //});

            var MemoryStream = window.memorystream;
            var stream = MemoryStream.createReadStream(data)
            console.log('convert string to stream')

            var db = findDB(name);
            db = db == null ? openDB(table) : db;
            if (db == null) {
                console.log('can not open db')
                return;
            } 

            db.load(stream).then(function (res) {
                console.log('load erfolg: ')
            }).catch(function (err) {
                console.log('load error: ', err);
            });
        },

        Destroy: function (name) {
            var db = openDB(name)
            if (db != null) {
                db.destroy().then(function (response) {
                    console.log('DB ' + name + ' is destroied!')
                    removeDB(name)
                }).catch(function (err) {
                    console.log(err);
                });
            };
        },

        RemoveDoc: function (docId, docRev, table) {
            removeDoc(docId, docRev, table);
        },
    };
});