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

export class SearchManager {
    private static data_list:search_item_data[] = null
	private static max_count = 20

   // 获取书列表
	public static getList():search_item_data[] {
		if(SearchManager.data_list) {
			return SearchManager.data_list
		}
		SearchManager.data_list = []
		let string = util.getStorage(config.storage_key.SEARCH_RECORD)
		if(string) {
			SearchManager.data_list = JSON.parse(string)
		}
		return SearchManager.data_list
	}
	
	// 保存列表
	private static saveLocalList() {
		util.setStorage(config.storage_key.SEARCH_RECORD, JSON.stringify(SearchManager.data_list))
	}

    // 异步检查
	public static async asyncCheckNameOnSearch(name:string, cb:Function) {
		let index = -1
		for (let i = 0; i < SearchManager.getList().length; i++) {
			let element = SearchManager.getList()[i]
			if(element.name == name) {
				index = i
				break
			}
		}
		cb && cb(index)
	}
	
	// 同步检查
	public static syncCheckNameOnSearch(name:string):number {
		let index = -1
		for (let i = 0; i < SearchManager.getList().length; i++) {
			let element = SearchManager.getList()[i]
			if(element.name == name) {
				index = i
				break
			}
		}
		return index
	}
	
	// 添加
	public static addName(name:string):search_item_data[] {
		let index = SearchManager.syncCheckNameOnSearch(name)
		if(index>-1) {
			SearchManager.getList().splice(index,1)
		} else {
			if(SearchManager.getList().length >= SearchManager.max_count) {
				SearchManager.getList().pop()
			}
		}
		let data = new search_item_data()
		data.name = name
		SearchManager.getList().unshift(data)
		
		SearchManager.saveLocalList()
		
		return SearchManager.getList()
	}
	
	// 删除
    public static deleteName(data_name_list:string[]) {
		for (let i = 0; i < data_name_list.length; i++) {
			let element = data_name_list[i]
			for (let j = 0; j < SearchManager.getList().length; j++) {
				let j_element = SearchManager.getList()[j]
				if(element==j_element.name) {
					SearchManager.getList().splice(j,1)
				}
			}
		}
		SearchManager.saveLocalList()
	}
	
	// 重置数据
	public static resetData(data_list:search_item_data[]) {
		SearchManager.data_list = data_list
		SearchManager.saveLocalList()
	}

}