<?php

use Acms\Services\Facades\Config;
use Acms\Services\Facades\Common;
use Acms\Services\Facades\Logger;
use Acms\Services\Facades\Application as App;
use Acms\Services\Form\Import;
use Acms\Services\Form\Authorization;

class ACMS_POST_Form_Import extends ACMS_POST
{
    /**
     * @inheritDoc
     */
    public function post()
    {
        @set_time_limit(0);

        if (!$this->checkAuth()) {
            return $this->Post;
        }

        try {
            $path = $_FILES['file']['tmp_name'];
            if (is_uploaded_file($path) === false) {
                throw new \RuntimeException('無効なファイルです。');
            }
            $yaml = Config::yamlLoad($path);

            $import = App::make('form.import');
            assert($import instanceof Import);
            $import->run(BID, $yaml);
            $this->Post->set('notice', $import->getFailedContents());
            $this->Post->set('import', 'success');

            Logger::info('フォームをインポートしました', [
                'data' => $yaml,
            ]);
        } catch (\Exception $e) {
            $this->addError($e->getMessage());

            Logger::notice('フォームのインポートに失敗しました。' . $e->getMessage(), Common::exceptionArray($e));
        }

        return $this->Post;
    }

    /**
     * check auth
     *
     * @return bool
     */
    private function checkAuth()
    {
        $authorization = App::make('form.authorization');
        assert($authorization instanceof Authorization);
        if (!$authorization->canEdit((int) SUID, BID)) {
            return false;
        }
        if (!isset($_FILES['file']['tmp_name']) || $_FILES['file']['tmp_name'] === '') {
            $this->addError('No file was uploaded.');
            return false;
        }
        if (is_uploaded_file($_FILES['file']['tmp_name']) === false) {
            $this->addError('Invalid file.');
            return false;
        }
        return true;
    }
}
