<?php

namespace DZ\ImageShield;

use XF;
use XF\Entity\User;
use XF\Entity\Option;
use XF\Http\Upload;
use XF\Util\File;
use function array_replace;

class Shield
{
    public const OPTION_VALUE_INHERIT = 0;
    public const OPTION_VALUE_ENABLED = 1;
    public const OPTION_VALUE_DISABLED = 2;

    public const KEY_REGISTRY_USER_SIGNATURES = 'dz_is_userSignatures';

    public const KEY_EXTRA_SKIP_SHIELD = '_dzImageShield_skip_protection';

    public static function shouldProtectUploads(User $user): bool
    {
        if ($user->user_id <= 0 || $user->Option === null) {
            return true;
        }

        $applyProtection = false;
        if ($user->hasPermission('general', 'dzImageShield_toggle')) {
            $userOption = (int) $user->Option->get('dz_is_enabled');
        } else {
            $userOption = self::OPTION_VALUE_ENABLED;
        }

        $globalOption = (int) XF::app()->options()->dzImageShield_enabled;
        if ($userOption === self::OPTION_VALUE_ENABLED
            || (
                $userOption === self::OPTION_VALUE_INHERIT
                && $globalOption === self::OPTION_VALUE_ENABLED
            )
        ) {
            $applyProtection = true;
        }

        return $applyProtection;
    }

    public static function getOverlayImagePath(): string
    {
        return 'internal-data://dz_imageshield/image.png';
    }

    public static function storeUserOverlayText(int $userId, string $value): void
    {
        $custom = XF::app()->registry()->get(self::KEY_REGISTRY_USER_SIGNATURES);
        if (!is_array($custom)) {
            $custom = [];
        }
        if (strlen($value) === 0) {
            if (isset($custom[$userId])) {
                unset($custom[$userId]);
            }
        } else {
            $custom[$userId] = $value;
        }

        XF::app()->registry()->set(self::KEY_REGISTRY_USER_SIGNATURES, $custom);
    }

    public static function getUserOverlayText($userId): string
    {
        $custom = XF::app()->registry()->get(self::KEY_REGISTRY_USER_SIGNATURES);
        if (!is_array($custom)) {
            return '';
        }

        return $custom[$userId] ?? '';
    }

    public static function storeOverlayImage(Upload $file): string
    {
        $baseFile = $file->getTempFile();
        $output = self::getOverlayImagePath();

        File::copyFileToAbstractedPath($baseFile, $output);

        /** @var Option $option */
        $option = XF::em()->find('XF:Option', 'dzImageShield_signature');
        $option->option_value = array_replace((array) $option->option_value, [
            'type' => 'image'
        ]);

        $option->save();

        return $output;
    }
}
