package com.itant.shiwushu.manager;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.itant.shiwushu.bean.City;
import com.itant.shiwushu.bean.Province;
import com.itant.shiwushu.temp.TempCity;
import com.itant.shiwushu.temp.TempProvince;
import com.itant.shiwushu.tool.StringTool;

import java.io.IOException;
import java.util.List;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmList;
import io.realm.RealmResults;

/**
 * Created by Jason on 2018/10/7.
 */

public class RealmManager {
    private static RealmManager instance;
    private List<Province> provinceList;

    private RealmManager() {

    }

    public static RealmManager getInstance() {
        if (instance == null) {
            init();
        }
        return instance;
    }

    private static synchronized void init() {
        if (instance == null) {
            instance = new RealmManager();
        }
    }

    public void initRealm(Context context) {
        Realm.init(context);
        RealmConfiguration realmConfig = new RealmConfiguration.Builder()
                .assetFile("data/city.realm")
                .schemaVersion(1)
                //.name("city.realm")
                //.directory(Environment.getExternalStorageDirectory())
                .build();
        Realm.setDefaultConfiguration(realmConfig);

        // 在SD卡制作好数据库文件之后，上传到assets文件夹，以后就直接用assets文件夹里的数据库了
        //parseCityData(context);
        loadProvinceListFromDB();
    }

    /**
     * 从文件读取JSON字符串并解析成为对象
     */
    private void parseCityData(final Context context) {
        // 从assets里读取城市的json字符串，耗时操作
        ExecutorManager.getInstance().getFixedExecutor().submit(new Runnable() {
            @Override
            public void run() {
                try {
                    String json = StringTool.getStringFromAssets(context, "data/cities.txt");
                    List<TempProvince> provinceList = JSON.parseArray(json, TempProvince.class);
                    saveCityDataToDB(provinceList);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 保存数据到数据库，以提高查询效率
     */
    private void saveCityDataToDB(List<TempProvince> tempProvinceList) {
        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();

        int provinceId = 0;
        int cityId = 0;
        Province allProvince = realm.createObject(Province.class, provinceId);
        allProvince.setName("全部");
        RealmList<City> allCityRealmList = new RealmList<>();
        City allCity = realm.createObject(City.class, cityId);
        allCity.setName("全部");
        allCity.setProvinceName("全部");
        allCityRealmList.add(allCity);
        allProvince.setCity(allCityRealmList);

        for (TempProvince tempProvince : tempProvinceList) {
            provinceId++;
            Province province = realm.createObject(Province.class, provinceId);
            province.setName(tempProvince.getName());

            List<TempCity> tempCityList = tempProvince.getCity();
            RealmList<City> cityRealmList = new RealmList<>();
            for (TempCity tempCity : tempCityList) {
                cityId++;
                City city = realm.createObject(City.class, cityId);
                city.setName(tempCity.getName());
                city.setProvinceName(tempProvince.getName());
                cityRealmList.add(city);
            }
            province.setCity(cityRealmList);
        }
        realm.commitTransaction();
    }

    /**
     * 从数据库加载省市数据到内存，方便使用
     */
    private void loadProvinceListFromDB() {
        ExecutorManager.getInstance().getFixedExecutor().submit(new Runnable() {
            @Override
            public void run() {
                Realm realm = Realm.getDefaultInstance();
                RealmResults<Province> provinceRealmResults = realm.where(Province.class).findAll();
                // 及时关闭数据库，回收资源，如果是Activity里使用，则onCreate里getInstance，onDestroy里close，一般都是成对出现
                provinceList = realm.copyFromRealm(provinceRealmResults);
                realm.close();
            }
        });
    }

    public List<Province> getProvinceList() {
        return provinceList;
    }
}
