package com.gh.gamecenter.db;

import android.content.Context;

import com.gh.gamecenter.db.info.SearchHistoryInfo;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SearchHistoryDao {
	
	private DatabaseHelper helper;
	private Dao<SearchHistoryInfo, String>dao;

	public SearchHistoryDao(Context context){
		try{
			helper = DatabaseHelper.getHelper(context);
			dao = helper.getDao(SearchHistoryInfo.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void add(String item){
		try{
			dao.createOrUpdate(new SearchHistoryInfo(item));
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
	}
	
	public void delete(String item){
		try {
			dao.deleteById(item);
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
	}
	
	public void deleteAll(){
		
		CloseableIterator<SearchHistoryInfo> iterator = dao.iterator();
		while(iterator.hasNext()){
			try {
				dao.delete(iterator.next());
			} catch (SQLException e) {
				
				e.printStackTrace();
			}
		}
		return;
	}
	
	public List<String> getAll(){
		List<String> history = new ArrayList<String>();
		
		try {
			List<SearchHistoryInfo> his = dao.queryBuilder().orderBy("time", false).query();
			Iterator<SearchHistoryInfo> hisIterator = his.iterator();
			while(hisIterator.hasNext()){
				history.add(hisIterator.next().getItem());
			}
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		return history;
	}
	

}
