package com.navinfo.outdoor.util;

import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.vividsolutions.jts.geom.Geometry;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.BitSet;
import java.util.HashMap;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class Geohash {

	private	Geohash(){}

	private static class GeohashInstance{
		private static final Geohash INSTANCE = new Geohash();
	}

	public static Geohash getInstance(){
		return GeohashInstance.INSTANCE;
	}

	private static int numbits = 6 * 5;
	/*
	 * final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7',
	 * '8', '9', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p',
	 * 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
	 */
	// 为了加密，所以改了base32编码代码表
	final static char[] digits = { 'd', 'f', 'g', 'y', 'n', 't', 'u', 'v', 'q',
			'b', '9', 's', 'z', '7', 'i', '2', 'h', '5', '0', 'p', '4', 'm',
			'8', 'x', 'c', 'j', '6', 'e', '1', 'r', '3', 'k' };

	final static HashMap<Character, Integer> lookup = new HashMap<Character, Integer>();
	static {
		int i = 0;
		for (char c : digits)
			lookup.put(c, i++);
	}

//	public static void main(String[] args) {
//		String s = "1rn7exd5uhxy";
//		System.out.println(s);
//		System.out.println(new Geohash().decode(s)[0]);
//		System.out.println(new Geohash().decode(s)[1]);
//		System.out.println(new Geohash().encode(40.073556024581194, 116.24643344432116));
//	}

	//数据解密
	/**
	 * @param geohash 需要被解密的字符串
	 * @return double[] 经纬度double数组，纬度(latitude)在前,经度在后(longitude)
	 * */
	public String decode(String geohash) {
//		try {
//			StringBuilder buffer = new StringBuilder();
//			for (char c : geohash.toCharArray()) {
//
//				int i = lookup.get(c) + 32;
//				buffer.append(Integer.toString(i, 2).substring(1));
//			}
//
//			long a = Long.parseLong(buffer.toString(), 2);
//			buffer.setLength(0);
//			buffer.append(Long.toBinaryString(a));
//
//			BitSet lonset = new BitSet();
//			BitSet latset = new BitSet();
//
//			// even bits
//			int j = 0;
//			for (int i = 0; i < numbits * 2; i += 2) {
//				boolean isSet = false;
//				if (i < buffer.length())
//					isSet = buffer.charAt(i) == '1';
//				lonset.set(j++, isSet);
//			}
//
//			// odd bits
//			j = 0;
//			for (int i = 1; i < numbits * 2; i += 2) {
//				boolean isSet = false;
//				if (i < buffer.length())
//					isSet = buffer.charAt(i) == '1';
//				latset.set(j++, isSet);
//			}
//
//			double lon = decode(lonset, -180, 180);
//			double lat = decode(latset, -90, 90);
//
//			return new double[] { lat, lon };
//		} catch (RuntimeException re) {
//			re.printStackTrace();
//			return null;
//		}
		try {
			return Base64.desDecrypt(geohash);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	private double decode(BitSet bs, double floor, double ceiling) {
		double mid = 0;
		for (int i = 0; i < bs.length(); i++) {
			mid = (floor + ceiling) / 2;
			if (bs.get(i))
				floor = mid;
			else
				ceiling = mid;
		}
		return mid;
	}

//数据加密
	/**
	 * @param lat,lon   需要被加密的double  值
	 * */
	public String encode(double lat, double lon) {
//		BitSet latbits = getBits(lat, -90, 90);
//		BitSet lonbits = getBits(lon, -180, 180);
//		StringBuilder buffer = new StringBuilder();
//		for (int i = 0; i < numbits; i++) {
//			buffer.append((lonbits.get(i)) ? '1' : '0');
//			buffer.append((latbits.get(i)) ? '1' : '0');
//		}
		Geometry geometry = GeometryTools.createGeometry(new LatLng(lat, lon));
		try {
			return Base64.desEncrypt(geometry.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private BitSet getBits(double lat, double floor, double ceiling) {
		BitSet buffer = new BitSet(numbits);
		for (int i = 0; i < numbits; i++) {
			double mid = (floor + ceiling) / 2;
			if (lat >= mid) {
				buffer.set(i);
				floor = mid;
			} else {
				ceiling = mid;
			}
		}
		return buffer;
	}

	public static String base32(long i) {
		char[] buf = new char[65];
		int charPos = 64;
		boolean negative = (i < 0);
		if (!negative)
			i = -i;
		while (i <= -32) {
			buf[charPos--] = digits[(int) (-(i % 32))];
			i /= 32;
		}
		buf[charPos] = digits[(int) (-i)];

		if (negative)
			buf[--charPos] = '-';
		return new String(buf, charPos, (65 - charPos));
	}



}
