<?php


namespace CubiStore\Web\Service;

use ApkParser\Manifest;
use ApkParser\Parser;
use CubiStore\Web\Model\App;
use CubiStore\Web\Model\Release;
use CubiStore\Web\Utils\Apk;
use Doctrine\ORM\EntityManager;

class AppService
{
    /**
     * @var EntityManager
     */
    private $entityManager;

    /**
     * AppService constructor.
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function hasApprovedApp(string $name): bool
    {
        /** @var App|null $app */
        $app = $this->entityManager
            ->getRepository(App::class)
            ->findOneBy(['name' => $name, 'status' => App::STATUS_APPROVED]);

        return $app !== null;
    }

    public function createApp(Apk $apk): App
    {
        $app = new App();
        $app->setName($apk->getPackageName());
        $app->setLabel($apk->getLabel());

        return $app;
    }

    public function createRelease(Apk $apk, App $app, string $file): Release
    {
        $release = new Release();
        $release->setApp($app);
        $release->setVersionCode($apk->getVersionCode());
        $release->setVersionName($apk->getVersionName());
        $release->setApk($file);

        return $release;
    }

    public function getStorePath(App $app, Apk $apk): string
    {
        return __DIR__ . '/../../var/storage/apk/' . $app->getName() . '/' . $app->getId() . '/' . $apk->getVersionCode();
    }
}
