import {defineStore} from 'pinia';
import { book_item_data, book_read_data, read_record_data } from '../data/data';
import { config } from '../config/config';
import { util } from '../framework/util';
export const ReadRecord = defineStore('read-record',()=>{
	let data:Map<string,string> = null
	function getData():Map<string,string> {
		// util.removeStorageForKey(config.storage_key.READ_RECORD)
		if(data) {
			return data
		}
		data = new Map<string,string>()
		let string = util.getStorage(config.storage_key.READ_RECORD)
		if(string) {
			let json_obj = JSON.parse(string)
			let map_obj:Map<string,string> = new Map(Object.entries(json_obj))
			data = map_obj
		}
		return data
	}
	function addData(book_data:book_item_data, read_data:book_read_data){
		let record_data = new read_record_data()
		record_data.chapter_id = read_data.book_chapter_id
		record_data.chapter_name = read_data.book_chapter_name
		let key = `${book_data.book_id}`
		getData().set(key, JSON.stringify(record_data))
				
		let data_string = JSON.stringify(Object.fromEntries(data))
		util.setStorage(config.storage_key.READ_RECORD, data_string)
	}
	
	function getReadRecordData(book_id:number):read_record_data {
		let value = getData().get(`${book_id}`)
		if(value) {
			let book_data = JSON.parse(value)
			return book_data
		}
		return null
	}
	
	function deleteReadRecordData(book_id_list:number[]) {
		let is_delete:boolean = false
		for (let i = 0; i < book_id_list.length; i++) {
			let id = book_id_list[i]
			let key = `${id}`
			if(getData().has(key)) {
				console.log('删除的book_id=',id)
				getData().delete(key)
				is_delete = true
			}
		}
		if(is_delete) {
			let data_string = JSON.stringify(Object.fromEntries(getData()))
			util.setStorage(config.storage_key.READ_RECORD, data_string)
		}
	}
	
	return {data,getData,addData,getReadRecordData,deleteReadRecordData}
})