# Path: gogdb/updater/gogtoken.py
# class GogToken:
#     def __init__(self, aio_session, client_id=GALAXY_ID, client_secret=GALAXY_SECRET):
#         self.aio_session = aio_session
#         self.client_id = client_id
#         self.client_secret = client_secret
# 
#         self.lock = asyncio.Lock()
# 
#     @classmethod
#     def from_file(cls, aio_session, filename):
#         token = cls(aio_session)
#         token.load(filename)
#         return token
# 
#     @classmethod
#     async def from_code(cls, aio_session, login_code, client_id=GALAXY_ID, client_secret=GALAXY_SECRET):
#         token_query = {
#             "client_id": client_id,
#             "client_secret": client_secret,
#             "grant_type": "authorization_code",
#             "code": login_code,
#             "redirect_uri": REDIRECT_URL # Needed for origin verification
#         }
#         token_resp = await aio_session.get(TOKEN_URL, params=token_query)
#         token = cls(aio_session, client_id, client_secret)
#         token.set_data(await token_resp.json())
#         return token
# 
#     def set_data(self, token_data):
#         if "error" in token_data:
#             raise AuthError(token_data["error"], token_data["error_description"])
# 
#         if "client_id" in token_data:
#             self.client_id = token_data["client_id"]
#         if "client_secret" in token_data:
#             self.client_secret = token_data["client_secret"]
#         self.access_token = token_data["access_token"]
#         self.refresh_token = token_data["refresh_token"]
#         self.expires_in = timedelta(seconds=token_data["expires_in"])
#         self.scope = token_data["scope"]
#         self.session_id = token_data["session_id"]
#         self.token_type = token_data["token_type"]
#         self.user_id = token_data["user_id"]
#         if "created" in token_data:
#             self.created = datetime.fromtimestamp(
#                 token_data["created"], tz=timezone.utc)
#         else:
#             self.created = datetime.now(tz=timezone.utc)
# 
#     def get_data(self):
#         token_data = {
#             "client_id": self.client_id,
#             "client_secret": self.client_secret,
#             "access_token": self.access_token,
#             "refresh_token": self.refresh_token,
#             "expires_in": int(self.expires_in.total_seconds()),
#             "scope": self.scope,
#             "session_id": self.session_id,
#             "token_type": self.token_type,
#             "user_id": self.user_id,
#             "created": int(self.created.timestamp())
#         }
#         return token_data
# 
#     def load(self, filename):
#         with open(filename, "r") as f:
#             self.set_data(json.load(f))
# 
#     def save(self, filename):
#         with open(filename, "w") as f:
#             json.dump(self.get_data(), f, indent=2, sort_keys=True)
# 
#     async def refresh(self, refresh_token=None):
#         if refresh_token is None:
#             refresh_token = self.refresh_token
#         token_query = {
#             "client_id": self.client_id,
#             "client_secret": self.client_secret,
#             "grant_type": "refresh_token",
#             "refresh_token": refresh_token
#         }
#         token_resp = await self.aio_session.get(TOKEN_URL, params=token_query)
#         self.set_data(await token_resp.json())
# 
#     def expired(self, margin=timedelta(seconds=60)):
#         expires_at = self.created + self.expires_in
#         return (datetime.now(timezone.utc) - expires_at) > margin
# 
#     async def refresh_if_expired(self, refresh_token=None, margin=timedelta(seconds=60)):
#         await self.lock.acquire()
#         expired = self.expired(margin)
#         if expired:
#             await self.refresh(refresh_token)
#         self.lock.release()
#         return expired
# 
#     def __repr__(self):
#         return repr(self.__dict__)


import pathlib
import logging
import json
import zlib
import os
import aiohttp
import gogdb.core.storage as storage
from gogdb.updater.gogtoken import GogToken





CLIENT_VERSION = "1.2.17.9" # Just for their statistics
USER_AGENT = f"GOGGalaxyClient/{CLIENT_VERSION} gogdb/2.0"
REQUEST_RETRIES = 3

# Caching constants
CACHE_NONE = 0      # Download without caching
CACHE_STORE = 1     # Download and store to disk
CACHE_LOAD = 2      # Only load from disk
CACHE_FALLBACK = 3  # Try to load, on failure fall back to store

logger = logging.getLogger("UpdateDB.session")

class GogSession:
    def __init__(self, db, config):
        self.db = db
        self.config = config
        self.storage_path = pathlib.Path(config["STORAGE_PATH"])
        aio_connector = aiohttp.TCPConnector(limit=10, limit_per_host=4)
        headers = {"User-Agent": USER_AGENT}
        self.aio_session = aiohttp.ClientSession(
            connector=aio_connector, headers=headers)
        self.set_cookie("gog_lc", "US_USD_en-US")
        self.load_token()

    def load_token(self):

# Path: gogdb/updater/gogtoken.py
# class GogToken:
#     def __init__(self, aio_session, client_id=GALAXY_ID, client_secret=GALAXY_SECRET):
#         self.aio_session = aio_session
#         self.client_id = client_id
#         self.client_secret = client_secret
# 
#         self.lock = asyncio.Lock()
# 
#     @classmethod
#     def from_file(cls, aio_session, filename):
#         token = cls(aio_session)
#         token.load(filename)
#         return token
# 
#     @classmethod
#     async def from_code(cls, aio_session, login_code, client_id=GALAXY_ID, client_secret=GALAXY_SECRET):
#         token_query = {
#             "client_id": client_id,
#             "client_secret": client_secret,
#             "grant_type": "authorization_code",
#             "code": login_code,
#             "redirect_uri": REDIRECT_URL # Needed for origin verification
#         }
#         token_resp = await aio_session.get(TOKEN_URL, params=token_query)
#         token = cls(aio_session, client_id, client_secret)
#         token.set_data(await token_resp.json())
#         return token
# 
#     def set_data(self, token_data):
#         if "error" in token_data:
#             raise AuthError(token_data["error"], token_data["error_description"])
# 
#         if "client_id" in token_data:
#             self.client_id = token_data["client_id"]
#         if "client_secret" in token_data:
#             self.client_secret = token_data["client_secret"]
#         self.access_token = token_data["access_token"]
#         self.refresh_token = token_data["refresh_token"]
#         self.expires_in = timedelta(seconds=token_data["expires_in"])
#         self.scope = token_data["scope"]
#         self.session_id = token_data["session_id"]
#         self.token_type = token_data["token_type"]
#         self.user_id = token_data["user_id"]
#         if "created" in token_data:
#             self.created = datetime.fromtimestamp(
#                 token_data["created"], tz=timezone.utc)
#         else:
#             self.created = datetime.now(tz=timezone.utc)
# 
#     def get_data(self):
#         token_data = {
#             "client_id": self.client_id,
#             "client_secret": self.client_secret,
#             "access_token": self.access_token,
#             "refresh_token": self.refresh_token,
#             "expires_in": int(self.expires_in.total_seconds()),
#             "scope": self.scope,
#             "session_id": self.session_id,
#             "token_type": self.token_type,
#             "user_id": self.user_id,
#             "created": int(self.created.timestamp())
#         }
#         return token_data
# 
#     def load(self, filename):
#         with open(filename, "r") as f:
#             self.set_data(json.load(f))
# 
#     def save(self, filename):
#         with open(filename, "w") as f:
#             json.dump(self.get_data(), f, indent=2, sort_keys=True)
# 
#     async def refresh(self, refresh_token=None):
#         if refresh_token is None:
#             refresh_token = self.refresh_token
#         token_query = {
#             "client_id": self.client_id,
#             "client_secret": self.client_secret,
#             "grant_type": "refresh_token",
#             "refresh_token": refresh_token
#         }
#         token_resp = await self.aio_session.get(TOKEN_URL, params=token_query)
#         self.set_data(await token_resp.json())
# 
#     def expired(self, margin=timedelta(seconds=60)):
#         expires_at = self.created + self.expires_in
#         return (datetime.now(timezone.utc) - expires_at) > margin
# 
#     async def refresh_if_expired(self, refresh_token=None, margin=timedelta(seconds=60)):
#         await self.lock.acquire()
#         expired = self.expired(margin)
#         if expired:
#             await self.refresh(refresh_token)
#         self.lock.release()
#         return expired
# 
#     def __repr__(self):
#         return repr(self.__dict__)


# Path: gogdb/updater/gogsession.py
import pathlib
import logging
import json
import zlib
import os
import aiohttp
import gogdb.core.storage as storage
from gogdb.updater.gogtoken import GogToken






CLIENT_VERSION = "1.2.17.9" # Just for their statistics
USER_AGENT = f"GOGGalaxyClient/{CLIENT_VERSION} gogdb/2.0"
REQUEST_RETRIES = 3

# Caching constants
CACHE_NONE = 0      # Download without caching
CACHE_STORE = 1     # Download and store to disk
CACHE_LOAD = 2      # Only load from disk
CACHE_FALLBACK = 3  # Try to load, on failure fall back to store

logger = logging.getLogger("UpdateDB.session")

class GogSession:
    def __init__(self, db, config):
        self.db = db
        self.config = config
        self.storage_path = pathlib.Path(config["STORAGE_PATH"])
        aio_connector = aiohttp.TCPConnector(limit=10, limit_per_host=4)
        headers = {"User-Agent": USER_AGENT}
        self.aio_session = aiohttp.ClientSession(
            connector=aio_connector, headers=headers)
        self.set_cookie("gog_lc", "US_USD_en-US")
        self.load_token()

    def load_token(self):

        self.token = GogToken(self.aio_session)