package com.cool.store.utils;
import java.util.BitSet;
/**
 * @Author suzhuhong
 * @Date 2025/4/1 20:39
 * @Version 1.0
 */

public class GeoHashUtils {
    private static final String BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz";
    private static final int[] BITS = {16, 8, 4, 2, 1};

    public static String encode(double lat, double lon, int precision) {
        BitSet latBits = getBits(lat, -90, 90);
        BitSet lonBits = getBits(lon, -180, 180);

        StringBuilder hash = new StringBuilder();
        for (int i = 0; i < precision; i++) {
            int index = 0;
            for (int j = 0; j < 5; j++) {
                boolean lonBit = lonBits.get(i * 5 + j);
                boolean latBit = latBits.get(i * 5 + j);
                index = (index << 1) | (lonBit ? 1 : 0);
                index = (index << 1) | (latBit ? 1 : 0);
            }
            hash.append(BASE32.charAt(index));
        }
        return hash.toString();
    }

    private static BitSet getBits(double val, double min, double max) {
        BitSet bits = new BitSet();
        for (int i = 0; i < 30; i++) {
            double mid = (min + max) / 2;
            if (val >= mid) {
                bits.set(i);
                min = mid;
            } else {
                max = mid;
            }
        }
        return bits;
    }
}