import Dexie from "dexie";

const DB_NAME = 'Truck_Monitor1';

export default class IndexDB {
    constructor(root) {
        this.db = null;
        this.version = 1
        this.root = root
        this.openLocalDB()
    }

    async openLocalDB () {
        this.db = new Dexie(DB_NAME)
        try {
            this.db && await this.db.open()
            this.version = this.db.verno
        } catch (error) {
            return console.warn('No data is stored yet!', error)
        }
        // 需要获取db的当前的version，再升级的时候存储新的store
        // this.version = this.db.verno
    }

    async initStore (list) {
        let msg = {}
        list.forEach(item => {
            msg[item] = 'version'
        })
        let version = parseInt(this.db.verno, 10)
        console.log(version)
        version = version || 1

        await this.db.close()
        console.log('dbOpen', this.db.isOpen())
        this.db.version(version + 1).stores(msg)
        this.version = version + 1
        await this.db.open()
    }

    async compareTable(list) {
        let tables = this.db.tables.map(item => item.name)
        if (tables.length !== list.length) {
            let initList = []
            list.forEach(item => {
                if (!tables.includes(item)) {
                    initList.push(item.layerName)
                }
            })
            await this.initStore(initList)
        }
    }

    async storeData(name, msg, version) {
        await this.db.open()
        let storeTable;
        try {
            storeTable = this.db.table(name)
            if (storeTable) {
                await storeTable.clear()
            }
            
            let data = {msg, version}
            this.db.transaction('rw', storeTable, () => {
                storeTable.put(data)
            }).then(() => {
                console.log(`added ${name}`)
            }).catch(err => {
                console.warn(err)
            })
        } catch (error) {
            console.error(error)
            storeTable = null;
        }
    }

    async getStoreData(name, version) {
        try{
            if (!this.db.isOpen()) {
                await this.db.open()
            }
            if (this.db.tables.length && this.db.table(name)) {
                return this.db.table(name).get({ version })
            } else {
                return new Promise((resolve) => {
                    resolve('')
                })
            }
        } catch(error) {
            console.warn(error)
            return new Promise((resolve) => {
                resolve('')
            })
        }
    }
} 