<commit_before><?php

namespace App\BusinessLogicLayer\managers;

use App\BusinessLogicLayer\WindowsBuilder;
use App\Models\GameFlavor;
use App\Models\ResourceFile;
use App\StorageLayer\GameFlavorStorage;
use App\Models\User;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Madnest\Madzipper\Madzipper;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Exception;

include_once 'functions.php';

/**
 * Contains the functionality, methods and handling logic for the @see GameFlavor class
 *
 * Class GameFlavorManager
 * @package App\BusinessLogicLayer\managers
 */
class GameFlavorManager {

    private $gameFlavorStorage;
    //the string that will be used to name the final jnlp file
    //private $JNLP_FILE_PREFIX = "game";
    private $fileManager;

    public function __construct() {
        $this->gameFlavorStorage = new GameFlavorStorage();
        $this->fileManager = new FileManager();
    }

    public function getJarFilePathForGameFlavor($gameFlavorId) {
        return storage_path() . '/app/data_packs/additional_pack_'. $gameFlavorId . '/memori.jar';
    }


    //TODO: refactor separate into create and edit
    /**
     * @param $gameFlavorId int id of the game flavor
     * @param array $inputFields contain the game flavor parameters
     * @return GameFlavor the newly created instance
     * @internal param Request $request the request object
     */
    public function createGameFlavor($gameFlavorId, array $inputFields) {

        if ($gameFlavorId == null) {
            //create new instance
            $inputFields['creator_id'] = Auth::user()->id;
            $gameFlavor = new GameFlavor;
            $gameFlavor = $this->assignValuesToGameFlavor($gameFlavor, $inputFields);
            $gameFlavor->game_version_id = $inputFields['game_version_id'];
            $gameFlavor->creator_id = $inputFields['creator_id'];
        } else {
            //edit existing
            $gameFlavor = $this->getGameFlavor($gameFlavorId);

            $gameFlavor = $this->assignValuesToGameFlavor($gameFlavor, $inputFields);
            $this->markGameFlavorAsSubmittedForApproval($gameFlavor->id);
        }
        DB::transaction(function() use($gameFlavor, $inputFields) {
            $imgManager = new ImgManager();
            if(!$gameFlavor->game_identifier)
                $gameFlavor->game_identifier = $this->createIdentifierForGameFlavor($gameFlavor);
            $gameFlavor = $this->gameFlavorStorage->storeGameFlavor($gameFlavor);

            if (isset($inputFields['cover_img'])) {
                $gameFlavor->cover_img_id = $imgManager->uploadGameFlavorCoverImg($gameFlavor, $inputFields['cover_img']);
                $resourceManager = new ResourceManager();
                $gameFlavorImgCoverFile = $resourceManager->getFileForResourceForGameFlavor($gameFlavor->coverImg, $gameFlavor->id);
                $this->convertGameFlavorCoverImgToIcon($gameFlavorImgCoverFile);
            }
            $gameFlavor->save();
        });
        return $gameFlavor;

    }

    public function assignGameFlavorToGameVersion($gameFlavorId, $gameVersionId) {
        $gameFlavor = $this->getGameFlavor($gameFlavorId);
        $gameVersionManager = new GameVersionManager();
        $gameVersion = $gameVersionManager->getGameVersion($gameVersionId);

        if(!$gameFlavor || !$gameVersion)
            throw new \Exception("ERROR game flavor id: " . $gameFlavorId . " or game version id: " . $gameVersionId . " do not exist");
        $gameFlavor->game_version_id = $gameVersion->id;
        $gameFlavor->save();
        return $gameFlavor;
    }

    private function createIdentifierForGameFlavor(GameFlavor $gameFlavor) {
        return greeklish($gameFlavor->name);
    }

    public function getResourceCategoriesForGameFlavor($gameFlavor, $langId) {
        $resourceCategoryManager = new ResourceCategoryManager();
        $resourceManager = new ResourceManager();
        $gameVersionResourceCategories = $resourceCategoryManager->getResourceCategoriesForGameVersionForLanguage($gameFlavor->game_version_id, $langId);
        foreach ($gameVersionResourceCategories as $category) {
            $currCatResources = $category->resources;
            foreach ($currCatResources as $resource) {
                $resourceFile = $resourceManager->getFileForResourceForGameFlavor($resource, $gameFlavor->id);
                if($resourceFile != null) {
                    $resource->file_path = $resourceFile->file_path;
                } else {
                    if(File::exists(storage_path('app/game_versions/data/' . $gameFlavor->game_version_id . '/' . $resource->name))) {
                        $resource->file_path = 'game_versions/data/' . $gameFlavor->game_version_id . '/' . $resource->name;
                    } else {
                        $resource->file_path = null;
                    }
                }
            }
        }
        return $gameVersionResourceCategories;
    }

    public function getGameFlavors() {
        $user = Auth::user();
        //if not logged in user, get only the published versions
        if($user != null) {
            if ($user->isAdmin()) {
                //if admin, get all game versions
                $gameFlavorsToBeReturned = $this->gameFlavorStorage->getAllGameFlavors();
            } else {
                //if regular user, merge the published game versions with the game versions created by the user
                $publishedGameFlavors = $this->gameFlavorStorage->getGameFlavorsByPublishedState(true);
                $gameFlavorsCreatedByUser = $this->gameFlavorStorage->getGameFlavorsByPublishedStateByUser(false, $user->id);

                $gameFlavorsToBeReturned = $gameFlavorsCreatedByUser->merge($publishedGameFlavors);
            }
        } else {
            $gameFlavorsToBeReturned = $this->gameFlavorStorage->getGameFlavorsByPublishedState(true);
        }

        foreach ($gameFlavorsToBeReturned as $gameFlavor) {
            $gameFlavor->cover_img_file_path = $gameFlavor->coverImg->file->file_path;
            $gameFlavor->accessed_by_user = $this->isGameFlavorAccessedByUser($gameFlavor, $user);
        }
        return $gameFlavorsToBeReturned;
    }

    private function getGameFlavorCoverImgFilePath(GameFlavor $gameFlavor) {
        $resource = $gameFlavor->coverImg;
        if($resource != null) {
            $resourceManager = new ResourceManager();
            $resourceFile = $resourceManager->getFileForResourceForGameFlavor($resource, $gameFlavor->id);
            if($resourceFile != null)
                return $resourceFile->file_path;
        }<commit_msg>Load correct cover image<commit_after><?php

namespace App\BusinessLogicLayer\managers;

use App\BusinessLogicLayer\WindowsBuilder;
use App\Models\GameFlavor;
use App\Models\ResourceFile;
use App\StorageLayer\GameFlavorStorage;
use App\Models\User;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Madnest\Madzipper\Madzipper;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Exception;

include_once 'functions.php';

/**
 * Contains the functionality, methods and handling logic for the @see GameFlavor class
 *
 * Class GameFlavorManager
 * @package App\BusinessLogicLayer\managers
 */
class GameFlavorManager {

    private $gameFlavorStorage;
    //the string that will be used to name the final jnlp file
    //private $JNLP_FILE_PREFIX = "game";
    private $fileManager;

    public function __construct() {
        $this->gameFlavorStorage = new GameFlavorStorage();
        $this->fileManager = new FileManager();
    }

    public function getJarFilePathForGameFlavor($gameFlavorId) {
        return storage_path() . '/app/data_packs/additional_pack_'. $gameFlavorId . '/memori.jar';
    }


    //TODO: refactor separate into create and edit
    /**
     * @param $gameFlavorId int id of the game flavor
     * @param array $inputFields contain the game flavor parameters
     * @return GameFlavor the newly created instance
     * @internal param Request $request the request object
     */
    public function createGameFlavor($gameFlavorId, array $inputFields) {

        if ($gameFlavorId == null) {
            //create new instance
            $inputFields['creator_id'] = Auth::user()->id;
            $gameFlavor = new GameFlavor;
            $gameFlavor = $this->assignValuesToGameFlavor($gameFlavor, $inputFields);
            $gameFlavor->game_version_id = $inputFields['game_version_id'];
            $gameFlavor->creator_id = $inputFields['creator_id'];
        } else {
            //edit existing
            $gameFlavor = $this->getGameFlavor($gameFlavorId);

            $gameFlavor = $this->assignValuesToGameFlavor($gameFlavor, $inputFields);
            $this->markGameFlavorAsSubmittedForApproval($gameFlavor->id);
        }
        DB::transaction(function() use($gameFlavor, $inputFields) {
            $imgManager = new ImgManager();
            if(!$gameFlavor->game_identifier)
                $gameFlavor->game_identifier = $this->createIdentifierForGameFlavor($gameFlavor);
            $gameFlavor = $this->gameFlavorStorage->storeGameFlavor($gameFlavor);

            if (isset($inputFields['cover_img'])) {
                $gameFlavor->cover_img_id = $imgManager->uploadGameFlavorCoverImg($gameFlavor, $inputFields['cover_img']);
                $resourceManager = new ResourceManager();
                $gameFlavorImgCoverFile = $resourceManager->getFileForResourceForGameFlavor($gameFlavor->coverImg, $gameFlavor->id);
                $this->convertGameFlavorCoverImgToIcon($gameFlavorImgCoverFile);
            }
            $gameFlavor->save();
        });
        return $gameFlavor;

    }

    public function assignGameFlavorToGameVersion($gameFlavorId, $gameVersionId) {
        $gameFlavor = $this->getGameFlavor($gameFlavorId);
        $gameVersionManager = new GameVersionManager();
        $gameVersion = $gameVersionManager->getGameVersion($gameVersionId);

        if(!$gameFlavor || !$gameVersion)
            throw new \Exception("ERROR game flavor id: " . $gameFlavorId . " or game version id: " . $gameVersionId . " do not exist");
        $gameFlavor->game_version_id = $gameVersion->id;
        $gameFlavor->save();
        return $gameFlavor;
    }

    private function createIdentifierForGameFlavor(GameFlavor $gameFlavor) {
        return greeklish($gameFlavor->name);
    }

    public function getResourceCategoriesForGameFlavor($gameFlavor, $langId) {
        $resourceCategoryManager = new ResourceCategoryManager();
        $resourceManager = new ResourceManager();
        $gameVersionResourceCategories = $resourceCategoryManager->getResourceCategoriesForGameVersionForLanguage($gameFlavor->game_version_id, $langId);
        foreach ($gameVersionResourceCategories as $category) {
            $currCatResources = $category->resources;
            foreach ($currCatResources as $resource) {
                $resourceFile = $resourceManager->getFileForResourceForGameFlavor($resource, $gameFlavor->id);
                if($resourceFile != null) {
                    $resource->file_path = $resourceFile->file_path;
                } else {
                    if(File::exists(storage_path('app/game_versions/data/' . $gameFlavor->game_version_id . '/' . $resource->name))) {
                        $resource->file_path = 'game_versions/data/' . $gameFlavor->game_version_id . '/' . $resource->name;
                    } else {
                        $resource->file_path = null;
                    }
                }
            }
        }
        return $gameVersionResourceCategories;
    }

    public function getGameFlavors() {
        $user = Auth::user();
        //if not logged in user, get only the published versions
        if($user != null) {
            if ($user->isAdmin()) {
                //if admin, get all game versions
                $gameFlavorsToBeReturned = $this->gameFlavorStorage->getAllGameFlavors();
            } else {
                //if regular user, merge the published game versions with the game versions created by the user
                $publishedGameFlavors = $this->gameFlavorStorage->getGameFlavorsByPublishedState(true);
                $gameFlavorsCreatedByUser = $this->gameFlavorStorage->getGameFlavorsByPublishedStateByUser(false, $user->id);

                $gameFlavorsToBeReturned = $gameFlavorsCreatedByUser->merge($publishedGameFlavors);
            }
        } else {
            $gameFlavorsToBeReturned = $this->gameFlavorStorage->getGameFlavorsByPublishedState(true);
        }

        foreach ($gameFlavorsToBeReturned as $gameFlavor) {
            $gameFlavor->cover_img_file_path = $this->getGameFlavorCoverImgFilePath($gameFlavor);
            $gameFlavor->accessed_by_user = $this->isGameFlavorAccessedByUser($gameFlavor, $user);
        }
        return $gameFlavorsToBeReturned;
    }

    private function getGameFlavorCoverImgFilePath(GameFlavor $gameFlavor) {
        $resource = $gameFlavor->coverImg;
        if($resource != null) {
            $resourceManager = new ResourceManager();
            $resourceFile = $resourceManager->getFileForResourceForGameFlavor($resource, $gameFlavor->id);
            if($resourceFile != null)
                return $resourceFile->file_path;
        }
{'fraction_non_alphanumeric': 0.10808629292632815, 'fraction_numerical': 0.0, 'mean_word_length': 2.891776127926899, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 125, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3222060', 'n_tokens_mistral': 3818, 'n_tokens_neox': 3723, 'n_words': 691}