package com.kfzs.duanduan.db;


import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kfzs.duanduan.KFZSApp;
import com.kfzs.duanduan.bean.SearchRecordBean;

import java.util.List;

/**
 * @ Created by Dlg
 * @ <p>TiTle:  SearchRecordHelper</p>
 * @ <p>Description:搜索历史的记录保存帮助类</p>
 * @ date:  2017/8/19 9:54
 * @ QQ:    315096953
 */

public class SearchRecordHelper {

    private static SearchRecordHelper mSearchRecordHelper;
    private SharedPreferences mSp;
    private final String SEARCH_RECORD_FILE = "SEARCH_RECORD";
    private final String SEARCH_RECORD = "SEARCH_RECORD";
    private final int MAX_RECORDS = 6;//最大保存的记录数量


    public static SearchRecordHelper getInstance() {
        if (mSearchRecordHelper == null) {
            mSearchRecordHelper = new SearchRecordHelper();
            mSearchRecordHelper.mSp = KFZSApp.getInstance()
                    .getSharedPreferences(mSearchRecordHelper.SEARCH_RECORD_FILE, Context.MODE_PRIVATE);
        }
        return mSearchRecordHelper;
    }

    /**
     * 添加记录，会自动过滤重复，自动限制为10个最新记录
     *
     * @param searchRecordBean
     * @return
     */
    public List<SearchRecordBean> addRecordList(SearchRecordBean searchRecordBean) {
        List<SearchRecordBean> list = getRecordList();
        deleteSameRecord(searchRecordBean, list);
        if (list.size() > MAX_RECORDS - 1) {
            list = list.subList(0, MAX_RECORDS - 1);
        }
        list.add(0, searchRecordBean);
        setRecordList(list);
        return list;
    }

    /**
     * @param searchRecordBean
     * @param list             会自动把这个list中的相同项删除
     */
    public void deleteSameRecord(SearchRecordBean searchRecordBean, List<SearchRecordBean> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getKey()
                    .equals(searchRecordBean.getKey())) {
                list.remove(i);
                while (list.size() > MAX_RECORDS) {
                    list.remove(list.size() - 1);
                }
                setRecordList(list);
                return;
            }
        }
    }

    public void clearList() {
        mSp.edit().putString(SEARCH_RECORD, "[]").commit();
    }

    private void setRecordList(List<SearchRecordBean> list) {
        if (list.size() > MAX_RECORDS) {
            throw new RuntimeException("最大支持" + MAX_RECORDS + "条记录！");
        }
        mSp.edit().putString(SEARCH_RECORD, new Gson().toJson(list)).commit();
    }

    public List<SearchRecordBean> getRecordList() {
        List<SearchRecordBean> list = new Gson().fromJson(mSp.getString(SEARCH_RECORD, "[]"),
                new TypeToken<List<SearchRecordBean>>() {
                }.getType());

        return list;
    }
}
