from PIL import Image, ExifTags
import exifread
import pyheif
from pillow_heif import register_heif_opener
from findperson.imageface import ImageFaces
register_heif_opener()

ifs = None

def get_imagefaces(imgfile, imgid, userid):
	global ifs
	if ifs is None:
		ifs = ImageFaces()

	info = ifs.save_faces(userid, imgfile, imgid=imgid)
	return info

def get_heif_exif(imgfile):
	# 读取HEIC文件
	heif_file = pyheif.read(imgfile)

	# 将HEIC转换为PIL图像对象
	image = Image.frombytes(
		heif_file.mode,
		heif_file.size,
		heif_file.data,
		"raw",
		heif_file.mode,
		heif_file.stride,
	)

	# 提取EXIF数据
	exif_data = image.getexif()

	# 将EXIF数据转换为可读格式
	exif_data_dict = {
		ExifTags.TAGS.get(k, k): v
		for k, v in exif_data.items()
		if k in ExifTags.TAGS
	}
	return exif_data_dict

def convert_to_degrees(value):
	d = float(value.values[0].num) / float(value.values[0].den)
	m = float(value.values[1].num) / float(value.values[1].den)
	s = float(value.values[2].num) / float(value.values[2].den)

	return d + (m / 60.0) + (s / 3600.0)

def get_image_info(imgfile):
	"""
	从EXIF数据中提取纬度和经度信息。
	"""
	exif_data = None
	if imgfile.lower().endswith('heic'):
		exif_data = get_heif_exif(imgfile)
	else:
		with open(imgfile, 'rb') as f:
			exif_data = exifread.process_file(f)
	if exif_data is None:
		return None, None, None
	# 经度
	timestamp = None
	if 'EXIF DateTimeOriginal' in exif_data:
		timestamp = str(exif_data['EXIF DateTimeOriginal'])
		timestamp = timestamp[:19]
	lon_ref = exif_data.get('GPS GPSLongitudeRef')
	lon = exif_data.get('GPS GPSLongitude')
	lat_ref = exif_data.get('GPS GPSLatitudeRef')
	lat = exif_data.get('GPS GPSLatitude')
	glon = None
	glat = None
	try:
		if lon_ref and lon:
			glon = convert_to_degrees(lon)
			if lon_ref.values == 'W':
				glon = -lon

		# 纬度
		if lat_ref and lat:
			glat = convert_to_degrees(lat)
			if lat_ref.values == 'S':
				glat = -lat
	except:
		pass
	print(f'{imgfile=}, {glat=}, {glon=}, {timestamp=}')

	return glat, glon, timestamp

