package com.sagacloud.dict;

import com.sagacloud.endpoints.Dictionary;
import com.sagacloud.utils.OssUtils;
import com.sagacloud.utils.jsonHelper.geography.Geo;
import org.apache.commons.io.IOUtils;
import org.apache.htrace.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wo on 5/22/17.
 */
public class GeoStaticInfo {
    private static final Logger log = LoggerFactory.getLogger(GeoStaticInfo.class);
    public static Map<String, String> codeToNameMap = new HashMap<>();

    static {
        init();
    }

    public static void init(){
        codeToNameMap = new HashMap<>();
        try {
            String jsonStr = OssUtils.getFileAsString(Dictionary.geographyPath);
            ObjectMapper mapper = new ObjectMapper();
            Geo geo = mapper.readValue(jsonStr, Geo.class);
            geo.getNormal().stream().forEach(normal -> {
                normal.getProvinceInfo().stream().forEach(provinceInfo -> {
                    codeToNameMap.put(provinceInfo.getCode(), provinceInfo.getName());
                });
                normal.getCities().stream().forEach(city -> {
                    city.getCityInfo().stream().forEach(cityInfo -> {
                        codeToNameMap.put(cityInfo.getCode(), normal.getProvinceName() + cityInfo.getName());
                    });
                    city.getDistrict().stream().forEach(district -> {
                        codeToNameMap.put(district.getCode(), normal.getProvinceName() + city.getCityName() + district.getDistrictName());
                    });
                });
            });

            geo.getSpecialCities().stream().forEach(specialCity -> {
                specialCity.getCityInfo().stream().forEach(cityInfo2 -> {
                    codeToNameMap.put(cityInfo2.getCode(), cityInfo2.getName());
                });
                specialCity.getDistrict().stream().forEach(district2 -> {
                    codeToNameMap.put(district2.getCode(), specialCity.getName() + district2.getDistrictName());
                });
            });
            //港澳台特区
            geo.getSpecialDistrict().stream().forEach(specialDistrict -> {
                codeToNameMap.put(specialDistrict.getCode(),specialDistrict.getName());
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error(Arrays.toString(e.getStackTrace()));
        }
    }
}
