<?php

namespace Velis\Bpm\Email;

use RuntimeException;
use Velis\App;
use Velis\Bpm\Ticket\Post;
use Velis\Bpm\Ticket\Post\File as PostFile;
use Velis\Filesystem\FilesystemInterface;
use Velis\Lang;
use Velis\Model\File;
use WideImage\WideImage;

/**
 * Email attachment file model
 * @author Olek Procki <olo@velis.pl>
 */
class Attachment extends File
{
    /**
     * @return string
     */
    protected function _getTableName()
    {
        return 'app.email_message_attachment_tab';
    }


    /**
     * Returns attachments storage directory
     * @return string
     */
    protected function _getStorageDir()
    {
         return self::_getPrefixForStorageDir() . App::$config->upload->emailFilesDir . DIRECTORY_SEPARATOR;
    }


    /**
     * Returns url for downloading file
     * @return string
     */
    public function getDownloadUrl()
    {
        return '/email/message/download-attachment?attachment_id=' . $this->id();
    }


    /**
     * Returns related email message
     * @return \Velis\Bpm\Email\Message
     */
    public function getMessage()
    {
        return new Message($this->email_message_id);
    }


    /**
     * Removes file & row
     *
     * @param bool $erase
     * @return bool
     */
    public function remove($erase = true)
    {
        return parent::_remove($erase);
    }


    /**
     * Converts email attachment to post file
     *
     * @param Post $post
     * @return PostFile
     * @throws RuntimeException
     */
    public function toPostFile($post)
    {
        $file = new PostFile($this);
        $file['ticket_post_id'] = $post instanceof Post ? $post->id() : $post;
        $file['hash']           = md5('EmailAttachment' . microtime());

        if (!strlen(trim($file['filename']))) {
            $file['filename'] = $this->cid ? trim($this->cid, '<>') : Lang::get('EMAIL_ATTACHMENT') . $this->id();
        }

        if ($post instanceof Post) {
            $file['date_entered'] = $post['date_entered'];
        }
        $file->insert();

        /** @var FilesystemInterface $filesystem */
        $filesystem = App::$di->get('filesystem');

        if ($filesystem->has($this->getStoragePath())) {
            if ($filesystem->rename($this->getStoragePath(), $file->getStoragePath())) {
                $this->_remove(false);
                $isImage = in_array($file['type'], ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']);
                if ($isImage && $filesystem->has($file->getStoragePath()) && !$filesystem->has($file->getStoragePath(true))) {
                    $imageStr = $filesystem->read($file->getStoragePath());
                    $image = WideImage::loadFromString($imageStr);

                    $image = $image->resizeDown(200);
                    $thumbImageStr = $image->asString('png');

                    $filesystem->write($file->getStoragePath(true), $thumbImageStr);
                }
            } else {
                throw new RuntimeException(
                    Lang::get('GENERAL_STORAGE_PATH_ERROR')
                    . $this->getStoragePath() . ' do: ' . $file->getStoragePath()
                );
            }
        }

        return $file->load();
    }


    /**
     * Return attachment extension by filename
     *
     * @return string
     */
    public function getExtensionByName()
    {
        return end(explode('.', $this->filename));
    }
}
