<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author Daniele De Nobili
 * @package Application\Admin
 */

namespace Application\Admin\Form;

use Application\Core\Model\File;
use Pongho\EventDispatcher\Event;
use Pongho\FileUploader\FileUploader;
use Pongho\FileUploader\FileUploaderException;

/**
 * Campo file.
 *
 * @deprecated
 */
class FileField extends Field
{
    /**
     * Modello del file caricato.
     *
     * @var \Application\Core\Model\File
     */
    private $file;

    /**
     * {@inheritdoc}
     */
    public function setAttributeModel()
    {
        $controller = $this->get('subject');
        $request = $controller->getRequest();

        if ($request->files->has($this->post_name)) {
            try {
                $uploader = new FileUploader($request->files->get($this->post_name));
                $uploader
                    ->setPath($this->get('upload_path', null, true))
                    ->setAllowedExtensions($this->get('allowed_extensions', []))
                    ->setMaxFileSize($this->get('max_file_size', null))
                    ->setFilename($this->get('filename', null))
                    ->upload();

                /** @var \Application\Core\Model\Site $site */
                $site = $controller->getSite();

                $file_attributes = $uploader->getFileData();
                $file_attributes['site_id'] = $site->id;
                $file_attributes['path'] = substr((string) $file_attributes['path'], strlen($site->getUploadsPath()));

                $file_attributes = $controller->getContainer()->get('event_dispatcher')->filter(new Event($controller, 'admin.form.filter_file_attributes', ['model' => $this->model, 'uploader' => $uploader]), $file_attributes)->getReturnValue();

                if (is_numeric($file_id = $this->model->{$this->attribute_name})) {
                    $file = $this->getFileModel();

                    $this->model->{$this->attribute_name} = null;
                    $this->model->save(false);

                    $file->delete();
                }

                $file = File::create($file_attributes);

                $this->model->{$this->attribute_name} = $file->id;
            } catch (FileUploaderException $e) {
                $this->model->addError($this->attribute_name, $e->getMessage());
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getViewCode()
    {
        $attributes = array_merge($this->getBaseAttributes(), [
            'name' => $this->post_name,
            'id'   => $this->post_name,
            'type' => $this->getFieldType(),
        ]);

        $html = $this->get('subject')->getContainer()->get('template_html');
        $code = $html->generateTagInline('input', $attributes);

        if ($preview_link = $this->getPreviewLinkCode()) {
            $code .= ' ' . $preview_link;
        }

        if ($delete_link = $this->getDeleteLinkCode()) {
            $code .= ' ' . $delete_link;
        }

        return $code;
    }

    /**
     * Restituisce il codice per il link dell’anteprima del file.
     *
     * Restituisce `false` se il file non è ancora stato caricato.
     *
     * @return string
     */
    protected function getPreviewLinkCode()
    {
        if ($file = $this->getFileModel()) {
            $container = $this->get('subject')->getContainer();

            return $container->get('template_html')->generateTagBlock(
                'a',
                $container->get('language')->get('download'),
                [
                    'href' => $this->getFileModel()->path(),
                ]
            );
        }

        return false;
    }

    /**
     * Restituisce il codice per il link di eliminazione del file.
     *
     * Restituisce `false` se l’opzione `delete_path` non è impostata.
     *
     * @return string
     */
    protected function getDeleteLinkCode()
    {
        if ($this->has('delete_path') && $this->model->{$this->attribute_name}) {
            $container = $this->get('subject')->getContainer();

            return $container->get('template_html')->generateTagBlock(
                'a',
                $container->get('language')->get('delete'),
                [
                    'class' => 'delete',
                    'href'  => $this->get('subject')->url(sprintf($this->get('delete_path'), $this->model->{$this->attribute_name}, $this->model->id)),
                ]
            );
        }

        return false;
    }

    /**
     * Restituisce il tipo di campo.
     *
     * @return string
     */
    protected function getFieldType()
    {
        return 'file';
    }

    /**
     * Restituisce il modello del file.
     *
     * @return \Application\Core\Model\File
     */
    protected function getFileModel()
    {
        if ($this->file === null && is_numeric($file_id = $this->model->{$this->attribute_name})) {
            $this->file = File::find($file_id);
        }

        return $this->file;
    }
}
