<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

use Psr\Log\LoggerInterface;
use Shopware\Plugins\ViisonCommon\Classes\Installation\PluginStructureIntegrity;
use Shopware\Plugins\ViisonCommon\Classes\Util\Util as ViisonCommonUtil;

if (!class_exists('ViisonCommon_Plugin_BootstrapV13')) {
    require_once('PluginBootstrapV13.php');
}

/**
 * Version 14 of the common plugin Bootstrap class. This version is based on ViisonCommon_Plugin_BootstrapV13, but uses
 * our own logging service instead of Shopware's 'pluginlogger'.
 *
 * This class needs to be manually loaded in the respective plugin via:
 *
 * if (!class_exists('ViisonCommon_Plugin_BootstrapV14')) {
 *     require_once('ViisonCommon/PluginBootstrapV14.php');
 * }
 */
abstract class ViisonCommon_Plugin_BootstrapV14 extends ViisonCommon_Plugin_BootstrapV13
{
    /**
     * @var LoggerInterface
     */
    protected $logger = null;

    /**
     * @inheritdoc
     */
    protected function removeObsoletePluginFiles()
    {
        try {
            $pluginIntegrity = new PluginStructureIntegrity($this->Path(), $this->getLogger());
            $pluginIntegrity->removeObsoleteFiles();
        } catch (\Exception $e) {
            $this->getLogger()->error(
                $this->getName() . ': Failed to remove obsolete plugin files.',
                ['exception' => $e]
            );
        }
    }

    /**
     * {@inheritdoc}
     * @return LoggerInterface
     */
    protected function getLogger()
    {
        // Lazy initialization of the Logger because it has some performance advantages because then it is initialized
        // only when it is needed and not every site load.
        if (!$this->logger) {
            $this->logger = $this->get('viison_common.logger');
        }

        return $this->logger;
    }

    /**
     * @inheritdoc
     */
    protected function logException($message, \Exception $e)
    {
        $user = ViisonCommonUtil::getCurrentUser();

        $this->getLogger()->error(
            $message,
            [
                'pluginName' => $this->getName(),
                'versionNew' => $this->getVersion(),
                'user' => $user ? $user->getName() : null,
                'exception' => ViisonCommonUtil::exceptionToArray($e),
            ]
        );
    }
}
