import { book_item_data } from '../data/data';
import { util } from '../framework/util';
import { config } from '../config/config';

export class BookshelfManager {
    private static book_list:book_item_data[] = null
	
	// 获取书列表
	public static getBookList():book_item_data[] {
		if(BookshelfManager.book_list) {
			return BookshelfManager.book_list
		}
		BookshelfManager.book_list = []
		let string = util.getStorage(config.storage_key.BOOKSHELF_LIST)
		if(string) {
			BookshelfManager.book_list = JSON.parse(string)
		}
		return BookshelfManager.book_list
	}
	
	// 保存本地书列表
	public static saveLocalBookList() {
		util.setStorage(config.storage_key.BOOKSHELF_LIST, JSON.stringify(BookshelfManager.getBookList()))
	}

    // 检查在书架
	public static async checkBookOnBookshelf(book_id:number, cb:Function) {
		let on_bookshelf:boolean = false
		for (let i = 0; i < BookshelfManager.getBookList().length; i++) {
			let element = BookshelfManager.getBookList()[i]
			if(element.book_id == book_id) {
				on_bookshelf = true
				break
			}
		}
		cb && cb(on_bookshelf)
	}
	
	// 检查在书架(同步)
	public static syncCheckBookOnBookshelf(book_id:number):boolean {
		let on_bookshelf:boolean = false
		for (let i = 0; i < BookshelfManager.getBookList().length; i++) {
			let element = BookshelfManager.getBookList()[i]
			if(element.book_id == book_id) {
				on_bookshelf = true
				break
			}
		}
		return on_bookshelf
	}
	
	// 添加书
	public static addBook(book_data:book_item_data) {
		BookshelfManager.getBookList().unshift(book_data)
		BookshelfManager.saveLocalBookList()
	}
	
	// 删除书
	public static deleteBook(book_id_list:number[]) {
		for (let i = 0; i < book_id_list.length; i++) {
			let element = book_id_list[i]
			for (let j = 0; j < BookshelfManager.getBookList().length; j++) {
				let j_element = BookshelfManager.getBookList()[j]
				if(element==j_element.book_id) {
					BookshelfManager.getBookList().splice(j,1)
				}
			}
		}
		BookshelfManager.saveLocalBookList()
	}
	
	// 重置数据
	public static resetData(book_list:book_item_data[]) {
		BookshelfManager.book_list = book_list
		BookshelfManager.saveLocalBookList()
	}

}