const curVersion = 1

export function initDB() {
    return new Promise(resolve => {
        let openRequest = indexedDB.open("YaBL", curVersion);

        openRequest.onupgradeneeded = () => {
            console.log("init db!")
            let db = openRequest.result;
            if (!db.objectStoreNames.contains('books')) {
                db.createObjectStore('books', {keyPath: 'id'});
            }
            if (!db.objectStoreNames.contains('reader')) {
                db.createObjectStore('reader', {keyPath: 'id'});
            }
            resolve(true)
        };
        openRequest.onsuccess = () => {
            resolve(true)
        }
    })
}
export function addBook(id, bookInfo, contents) {
    return new Promise(async resolve => {
        await initDB()
        let openRequest = indexedDB.open("YaBL", curVersion);
        openRequest.onsuccess = () => {
            let db = openRequest.result;
            db.onversionchange = () => {
              db.close();
              alert("База данных устарела, пожалуйста, перезагрузите страницу.")
            };
            let transaction = db.transaction("books", "readwrite")
            let books = transaction.objectStore("books")
            books.add({
                id: id,
                ...bookInfo,
                contents: contents
            })
            resolve(true)
        };
        openRequest.onerror = () => {
            resolve(false)
        }
    })
}
export function removeBook(id) {
    return new Promise(async resolve => {
        await initDB()
        let openRequest = indexedDB.open("YaBL", curVersion);
        openRequest.onsuccess = () => {
            let db = openRequest.result;
            db.onversionchange = () => {
              db.close();
              alert("База данных устарела, пожалуйста, перезагрузите страницу.")
            };
            let transaction = db.transaction("books", "readwrite")
            let books = transaction.objectStore("books")
            books.delete(id)
            resolve(true)
        };
        openRequest.onerror = () => {
            resolve(false)
        }
    })
}

export function getBook(id) {
    return new Promise(async resolve => {
        await initDB()
        let openRequest = indexedDB.open("YaBL", curVersion);
        openRequest.onsuccess = () => {
            let db = openRequest.result;
            db.onversionchange = () => {
              db.close();
              alert("База данных устарела, пожалуйста, перезагрузите страницу.")
            };
            let transaction = db.transaction("books")
            let books = transaction.objectStore("books")
            let req = books.get(id)
            req.onsuccess = () => {
                if (req.result !== undefined) {
                  resolve(req.result)
                } else {
                  resolve(undefined)
                }
            };
        };
        openRequest.onerror = () => {
            resolve(false)
        }
    })
}
export function getAllBooks() {
    return new Promise(async resolve => {
        await initDB()
        let openRequest = indexedDB.open("YaBL", curVersion);
        openRequest.onsuccess = () => {
            let db = openRequest.result;
            db.onversionchange = () => {
              db.close();
              alert("База данных устарела, пожалуйста, перезагрузите страницу.")
            };
            let transaction = db.transaction("books")
            let books = transaction.objectStore("books")
            let req = books.getAll()
            req.onsuccess = () => {
                if (req.result !== undefined) {
                  resolve(req.result)
                } else {
                  resolve(undefined)
                }
            };
        };
        openRequest.onerror = () => {
            resolve(false)
        }
    })
}
export function getAllReadBooks() {
    return new Promise(async resolve => {
        await initDB()
        let openRequest = indexedDB.open("YaBL", curVersion);
        openRequest.onsuccess = () => {
            let db = openRequest.result;
            db.onversionchange = () => {
              db.close();
              alert("База данных устарела, пожалуйста, перезагрузите страницу.")
            };
            let transaction = db.transaction("reader")
            let reader = transaction.objectStore("reader")
            let req = reader.getAll()
            req.onsuccess = () => {
                if (req.result !== undefined) {
                  resolve(req.result)
                } else {
                  resolve(undefined)
                }
            };
        };
        openRequest.onerror = () => {
            resolve(false)
        }
    })
}
export function getReadBook(id) {
    return new Promise(async resolve => {
        await initDB()
        let openRequest = indexedDB.open("YaBL", curVersion);
        openRequest.onsuccess = () => {
            let db = openRequest.result;
            db.onversionchange = () => {
              db.close();
              alert("База данных устарела, пожалуйста, перезагрузите страницу.")
            };
            let transaction = db.transaction("reader")
            let reader = transaction.objectStore("reader")
            let req = reader.get(id)
            req.onsuccess = () => {
                if (req.result !== undefined) {
                  resolve(req.result)
                } else {
                  resolve(undefined)
                }
            };
        };
        openRequest.onerror = () => {
            resolve(false)
        }
    })
}
export function updateReadBook(id, progress) {
    return new Promise(async resolve => {
        await initDB()
        let openRequest = indexedDB.open("YaBL", curVersion);
        openRequest.onsuccess = () => {
            let db = openRequest.result;
            db.onversionchange = () => {
              db.close();
              alert("База данных устарела, пожалуйста, перезагрузите страницу.")
            };
            let transaction = db.transaction("reader", "readwrite")
            let reader = transaction.objectStore("reader")
            let prev = reader.get(id)
            prev.onsuccess = () => {
                reader.put({
                    id: id,
                    ...prev.result,
                    progress: progress,
                    lastRead: Math.floor(Date.now() / 1000)
                })
                resolve(true)
            }
        };
        openRequest.onerror = () => {
            resolve(false)
        }
    })
}
export function putReadBook(id, onBookshelf, bookInfo) {
    return new Promise(async resolve => {
        await initDB()
        let openRequest = indexedDB.open("YaBL", curVersion);
        openRequest.onsuccess = () => {
            let db = openRequest.result;
            db.onversionchange = () => {
              db.close();
              alert("База данных устарела, пожалуйста, перезагрузите страницу.")
            };
            let transaction = db.transaction("reader", "readwrite")
            let reader = transaction.objectStore("reader")
            let prev = reader.get(id)
            prev.onsuccess = () => {
                reader.put({
                    id: id,
                    ...prev.result,
                    onBookshelf: onBookshelf,
                    bookInfo: onBookshelf ? {
                        title: bookInfo.title,
                        authors: bookInfo.authors,
                    } : {}
                })
                resolve(true)
            }
        };
        openRequest.onerror = () => {
            resolve(false)
        }
    })
}
export function saveReadBook(id, offline) {
    return new Promise(async resolve => {
        await initDB()
        let openRequest = indexedDB.open("YaBL", curVersion);
        openRequest.onsuccess = () => {
            let db = openRequest.result;
            db.onversionchange = () => {
              db.close();
              alert("База данных устарела, пожалуйста, перезагрузите страницу.")
            };
            let transaction = db.transaction("reader", "readwrite")
            let reader = transaction.objectStore("reader")
            let prev = reader.get(id)
            prev.onsuccess = () => {
                reader.put({
                    id: id,
                    ...prev.result,
                    offline: offline,
                })
                resolve(true)
            }
        };
        openRequest.onerror = () => {
            resolve(false)
        }
    })
}
export function syncReadBook(syncData) {
    return new Promise(async resolve => {
        await initDB()
        let openRequest = indexedDB.open("YaBL", curVersion);
        openRequest.onsuccess = () => {
            let db = openRequest.result;
            db.onversionchange = () => {
              db.close();
              alert("База данных устарела, пожалуйста, перезагрузите страницу.")
            };
            let transaction = db.transaction("reader", "readwrite")
            let reader = transaction.objectStore("reader")
            reader.clear()
            if (syncData === null) {resolve(true); return}
            for (let book of syncData) {
                reader.add(book)
            }
            resolve(true)
        };
        openRequest.onerror = () => {
            resolve(false)
        }
    })
}