import {Helper, MyDb} from "../../../../js/lib/pwa-lib";

export class WordRotatorDb extends MyDb {

    static getInstance() {
        if (Helper.isNull(WordRotatorDb.instance)) {
            WordRotatorDb.instance = new WordRotatorDb();
        }
        return WordRotatorDb.instance;
    }

    constructor() {
        super("wordRotator", 3);
    }

    upgrade(db, oldVersion, newVersion, e) {
        console.log("upgrading!");
        if (Helper.isNull(oldVersion) || oldVersion < 1 && newVersion >= 1) {
            let levelObjectStore = db.createObjectStore(WordRotatorDb.OBJECT_STORE.LEVEL, {"keyPath": "id"});
        }
        if (Helper.isNull(oldVersion) || oldVersion < 2 && newVersion >= 2) {
            let levelObjectStore = e.target.transaction.objectStore(WordRotatorDb.OBJECT_STORE.LEVEL);
            levelObjectStore.createIndex("played", ["deleted", "played", "difficulty", "id"], {"unique": false});
        }
        if (Helper.isNull(oldVersion) || oldVersion < 3 && newVersion >= 3) {
            let levelObjectStore = e.target.transaction.objectStore(WordRotatorDb.OBJECT_STORE.LEVEL);
            levelObjectStore.createIndex("difficulty", "difficulty", {"unique": false});
        }
    };

    async saveManyLevels(levels) {
        return this.saveMany(levels, WordRotatorDb.OBJECT_STORE.LEVEL).catch(e => {
            console.error("insert error!", e);
        });
    }

    async loadLevel(levelId) {
        return this.load(levelId, WordRotatorDb.OBJECT_STORE.LEVEL);
    }

    async loadNextLevel(rendererTypes) {
        let levels = await this.loadAll(WordRotatorDb.OBJECT_STORE.LEVEL);
        levels = levels.sort((a,b) => {
           return (a["difficulty"] - b["difficulty"]);
        });

        let wrongLevels = [];
        let newLevels = [];
        let difficulty = -1;
        for (let i = 0, n = levels.length; i < n; i++) {
            if ((difficulty < 0 || difficulty === levels[i]["difficulty"]) && !levels[i]["deleted"] && !levels[i]["played"] && rendererTypes.indexOf(levels[i]["rendererType"]) !== -1) {
                newLevels.push(levels[i]);
                difficulty = levels[i]["difficulty"];
            }
            else if (levels[i]["difficulty"] !== 0 && !levels[i]["deleted"] && !levels[i]["played"] ) {
                wrongLevels.push(levels[i]);
            }
        }

        if (newLevels.length === 0) {
            return null;
        }

        return newLevels[Math.round(Math.random() * newLevels.length) % newLevels.length];
    }

    async saveLevelPlayed(levelId) {
        const level = await this.loadLevel(levelId);
        level.played = true;
        return await this.saveObj(level, WordRotatorDb.OBJECT_STORE.LEVEL);
    }

    async countLevels(){

    }
}

WordRotatorDb.OBJECT_STORE = {
    LEVEL: "level",
};
WordRotatorDb.instance = null;
