package com.gh.gamecenter.db;

import android.content.Context;
import android.text.TextUtils;

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

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

public class AskSearchHistoryDao {

    private DatabaseHelper helper;
    private Dao<AskSearchHistoryInfo, String> dao;

    public AskSearchHistoryDao(Context context) {
        try {
            helper = DatabaseHelper.getHelper(context);
            dao = helper.getDao(AskSearchHistoryInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void add(String key, String communityId) {
        try {
            if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(communityId)) {
                dao.createOrUpdate(createInfo(key, communityId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    private AskSearchHistoryInfo createInfo(String key, String communityId) {
        try {
            List<AskSearchHistoryInfo> his = dao.queryBuilder().
                    orderBy("time", false).
                    where().eq("communityId", communityId).
                    query();
            for (AskSearchHistoryInfo next : his) {
                String dbKey = next.getKey();
                if (dbKey != null && dbKey.equals(key)) dao.delete(next);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new AskSearchHistoryInfo(key, communityId);
    }

    public void deleteAll() {
        CloseableIterator<AskSearchHistoryInfo> iterator = dao.iterator();
        while (iterator.hasNext()) {
            try {
                dao.delete(iterator.next());
            } catch (Exception e) {

                e.printStackTrace();
            }
        }
        return;
    }

    public List<String> getAll(String communityId) {
        List<String> history = new ArrayList<String>();

        try {
            List<AskSearchHistoryInfo> his = dao.queryBuilder().
                    orderBy("time", false).
                    where().eq("communityId", communityId).
                    query();
            Iterator<AskSearchHistoryInfo> hisIterator = his.iterator();
            while (hisIterator.hasNext()) {
                history.add(hisIterator.next().getKey());
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return history;
    }


}
