import os
import urllib


class OSAWeb:

    def __init__(self, core):
        self.core = core
        self.log = core.log

    def getText(self, url) -> str:
        code, data = self.getBytes(url)
        return code, data.decode("utf8") if data else ""

    def getBytes(self, url) -> bytes:
        self.log.d(f"Downloading: {url}")
        try:
            with urllib.request.urlopen(url, timeout=30) as response:
                return response.getcode(), response.read()
        except Exception as e:
            self.log.e(f"Download failed: {e}")
            return 500, None

    def getFileInDir(self, url: str, directory: str, filename: str = None) -> str:
        """Download file to directory"""
        if filename is None:
            filename = os.path.basename(url)

        file_path = os.path.join(directory, filename)
        self.core.files.mkdir(directory, parents=True)

        try:
            urllib.request.urlretrieve(url, file_path)
            self.log.d(f"Downloaded {url} to {file_path}")
            return file_path
        except Exception as e:
            self.log.e(f"Failed to download {url}: {e}")
            return None

    def check_internet(self) -> bool:
        """Check internet connection"""
        try:
            urllib.request.urlopen('http://www.google.com', timeout=5)
            return True
        except:
            return False

