#!/usr/bin/python3
# encoding=utf-8
#
# Copyright 2023 Sébastien Noel
# SPDX-License-Identifier: GPL-2.0-or-later

from __future__ import annotations

import logging
import os

from ..build import (PackagingTask)
from ..game import (GameData)
from ..util import (TemporaryUmask, mkdir_p)
from typing import (TYPE_CHECKING)

logger = logging.getLogger(__name__)

try:
    from PIL import Image
    have_pil = True
except ImportError:
    have_pil = False

if TYPE_CHECKING:
    from ..packaging import (PerPackageState)


class GOGGamesData(GameData):
    def construct_task(self, **kwargs) -> GOGGamesIconTask:
        return GOGGamesIconTask(self, **kwargs)


class GOGGamesIconTask(PackagingTask):
    def fill_extra_files(
        self,
        per_package_state: PerPackageState
    ) -> None:
        super().fill_extra_files(per_package_state)
        package = per_package_state.package
        destdir = per_package_state.destdir

        match self.game.shortname:
            case 'avp':
                input_ico_filename = 'goggame-1207665883.ico'
            case 'darkforces':
                input_ico_filename = 'goggame-1421404433.ico'
            case 'serious-sam-tfe':
                input_ico_filename = 'goggame-1207658876.ico'
            case 'serious-sam-tse':
                input_ico_filename = 'goggame-1207658877.ico'
            case _:
                raise AssertionError(
                    'Method should not be called for this package',
                )

        ico_file = os.path.join(
            destdir,
            self.packaging.substitute(
                package.install_to, package.name,
            ).strip('/'),
            input_ico_filename,
        )

        if not have_pil:
            logger.warning(
                'Unable to load PIL modules. '
                'No icons will get extracted from ICON files.'
            )
        elif not os.path.exists(ico_file):
            logger.warning('GOG ico file unavailable.')
        else:
            img = Image.open(ico_file)
            png_destdir = os.path.join(destdir, 'usr', 'share', 'icons',
                                                'hicolor', '256x256', 'apps')
            mkdir_p(png_destdir)
            png_file = os.path.join(png_destdir, self.game.shortname + '.png')
            with TemporaryUmask(0o022):
                img.save(png_file, sizes=(256, 256))


GAME_DATA_SUBCLASS = GOGGamesData
