package com.rv.component.utils;


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

/******
 * 记录上一次的经纬度
 */
public class LocationRecord {

    private final static String FILE_NAME = "location_cookie";

    private final static String KEY_LAT = "key_lat";

    private final static String KEY_LON = "key_lon";

    private static SharedPreferences preferences;

    private static SharedPreferences getPreference(Context context) {
        if (preferences == null) {
            synchronized (LocationRecord.class) {
                if (null == preferences) {
                    preferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
                }
            }
        }
        return preferences;
    }

    public static double getOrSavelatLatitude(Context context, int errorCode, double latLatitude) {
        if (errorCode == 61 || errorCode == 161) {
            saveLat(context, latLatitude);
        } else {
            latLatitude = getLat(context);
            if (latLatitude == 0d) {
                latLatitude = 22.954073;
            }
        }
        return latLatitude;
    }

    public static double getOrSaveLonLongitude(Context context, int errorCode, double lonLongitude) {
        if (errorCode == 61 || errorCode == 161) {
            saveLon(context, lonLongitude);
        } else {
            lonLongitude = getLon(context);
            if (lonLongitude == 0d) {
                lonLongitude = 113.881138;
            }
        }
        return lonLongitude;
    }

    public static void savePosition(Context context, int errorCode, double latLatitude, double lonLongitude) {
        if (errorCode == 61 || errorCode == 161) {
            LocationRecord.saveLat(context, latLatitude);
            LocationRecord.saveLon(context, lonLongitude);
        } else {
            latLatitude = LocationRecord.getLat(context);
            lonLongitude = LocationRecord.getLat(context);
            if (latLatitude == 0) {
                latLatitude = 23.05;
            }
            if (lonLongitude == 0) {
                lonLongitude = 113.75;
            }
        }
    }

    public static void saveLat(Context context, double s) {
        getPreference(context).edit().putString(KEY_LAT, String.valueOf(s)).commit();
    }

    public static double getLat(Context context) {
        return Double.valueOf(getPreference(context).getString(KEY_LAT, "0.00"));
    }

    public static void saveLon(Context context, double s) {
        getPreference(context).edit().putString(KEY_LON, String.valueOf(s)).commit();
    }

    public static double getLon(Context context) {
        return Double.valueOf(getPreference(context).getString(KEY_LON, "0.00"));
    }

}
