package com.gh.gamecenter.db;

import android.content.Context;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

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

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

public class SearchHistoryDao implements ISearchHistoryDao {

    private final MutableLiveData<List<String>> histories = new MutableLiveData<>();

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

    public SearchHistoryDao(Context context) {
        try {
            helper = DatabaseHelper.getHelper(context);
            dao = helper.getDao(SearchHistoryInfo.class);
            histories.postValue(getAll());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void add(String item) {
        AppExecutor.getIoExecutor().execute(() -> {
            try {
                dao.createOrUpdate(new SearchHistoryInfo(item));
                histories.postValue(getAll());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void delete(String item) {
        AppExecutor.getIoExecutor().execute(() -> {
            try {
                dao.deleteById(item);
                histories.postValue(getAll());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void deleteAll() {
        AppExecutor.getIoExecutor().execute(() -> {
            CloseableIterator<SearchHistoryInfo> iterator = dao.iterator();
            while (iterator.hasNext()) {
                try {
                    dao.delete(iterator.next());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            histories.postValue(Collections.emptyList());
        });
        return;
    }

    @Override
    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 (Exception e) {

            e.printStackTrace();
        }
        return history;
    }

    @Override
    public LiveData<List<String>> getHistoryLiveData() {
        return histories;
    }
}
