from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
import logging
from typing import Tuple, Optional

logger = logging.getLogger(__name__)

class MediaService:
    @staticmethod
    def _get_if_exist(data, key):
        if key in data:
            return data[key]
        return None

    @staticmethod
    def _convert_to_degrees(value) -> float:
        """EXIF koordináták (fok, perc, másodperc) konvertálása tizedes fokká."""
        d = float(value[0])
        m = float(value[1])
        s = float(value[2])
        return d + (m / 60.0) + (s / 3600.0)

    @classmethod
    def extract_gps_info(cls, file_path: str) -> Optional[Tuple[float, float]]:
        """Kiolvassa a GPS koordinátákat a képből."""
        try:
            image = Image.open(file_path)
            exif_data = image._getexif()
            if not exif_data:
                return None

            gps_info = {}
            for tag, value in exif_data.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_info[sub_decoded] = value[t]

            if gps_info:
                lat = cls._convert_to_degrees(gps_info['GPSLatitude'])
                if gps_info['GPSLatitudeRef'] != "N":
                    lat = 0 - lat

                lon = cls._convert_to_degrees(gps_info['GPSLongitude'])
                if gps_info['GPSLongitudeRef'] != "E":
                    lon = 0 - lon

                return lat, lon
        except Exception as e:
            logger.warning(f"Nem sikerült kiolvasni az EXIF adatokat: {e}")
            return None
        return None