<?php

Yii::import('xupload.actions.XUploadAction');

class XArticleAlbumUploadAction extends XUploadAction {

    public $article_id;

    public function run() {
        if (isset($_GET['article_id'])) {
            $this->article_id = $_GET['article_id'] * 1;
            parent::run();
        } else {
            return false;
        }
    }

    /**
     * Uploads file to temporary directory
     *
     * @throws CHttpException
     */
    protected function handleUploading() {
        $this->init();
        $model = $this->formModel;
        $model->{$this->fileAttribute} = CUploadedFile::getInstance($model, $this->fileAttribute);

        if ($model->{$this->fileAttribute} !== null) {
            $model->{$this->mimeTypeAttribute} = $model->{$this->fileAttribute}->getType();
            $model->{$this->sizeAttribute} = $model->{$this->fileAttribute}->getSize();

            $model->{$this->displayNameAttribute} = $this->getNewName($model->{$this->fileAttribute});
            $model->{$this->fileNameAttribute} = $model->{$this->displayNameAttribute};

            if ($model->validate()) {

                $path = $this->getPath();

                if (!is_dir($path)) {
                    mkdir($path, 0777, true);
                    chmod($path, 0777);
                }


                $model->{$this->fileAttribute}->saveAs($path . $model->{$this->fileNameAttribute});
                chmod($path . $model->{$this->fileNameAttribute}, 0777);

                $articleAlbum = new ArticleAlbum;

                $articleAlbum->article_id = $this->article_id;
                $articleAlbum->image = $model->{$this->fileNameAttribute};

                if (!$articleAlbum->save()) {
                    echo $articleAlbum->getErrors();
                    exit;
                }

                ImageHelper::resizeImage($articleAlbum->getThumbnailSizes(), $path, $articleAlbum->image);


                $returnValue = $this->beforeReturn();
                if ($returnValue === true) {
                    echo json_encode(array(array(
                            "name" => $model->{$this->displayNameAttribute},
                            "type" => $model->{$this->mimeTypeAttribute},
                            "size" => $model->{$this->sizeAttribute},
                            "url" => $this->getFileUrl($model->{$this->fileNameAttribute}),
                            "thumbnail_url" => $model->getThumbnailUrl($this->getPublicPath() . 'thumb/'),
                            "delete_url" => $this->getController()->createUrl($this->getId(), array(
                                "_method" => "delete",
                                'article_id' => $this->article_id,
                                "file" => $model->{$this->fileNameAttribute},
                            )),
                            "delete_type" => "POST"
                    )));
                } else {
                    echo json_encode(array(array("error" => $returnValue,)));
                    Yii::log("XUploadAction: " . $returnValue, CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction");
                }
            } else {
                echo json_encode(array(array("error" => $model->getErrors($this->fileAttribute),)));
                Yii::log("XUploadAction: " . CVarDumper::dumpAsString($model->getErrors()), CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction");
            }
        } else {
            throw new CHttpException(500, "Could not upload file");
        }
    }

    protected function getNewName($instance) {
        return uniqid() . "." . $instance->getExtensionName();
    }

    /**
     * Removes temporary file from its directory and from the session
     *
     * @return bool Whether deleting was meant by request
     */
    protected function handleDeleting() {
        if (isset($_GET["_method"]) && $_GET["_method"] == "delete") {
            $success = false;
            if ($_GET["file"][0] !== '.' && Yii::app()->user->hasState($this->stateVariable)) {
                // pull our userFiles array out of state and only allow them to delete
                // files from within that array
                $userFiles = Yii::app()->user->getState($this->stateVariable, array());

                if ($this->fileExists($userFiles[$_GET["file"]])) {

                    $articleAlbum = ArticleAlbum::model()->findByAttributes(array('article_id' => $this->article_id, 'image' => $_GET['file']));
                    if ($articleAlbum !== NULL) {
                        $articleAlbum->delete();
                    }
                    if (isset($userFiles[$_GET["file"]])) {
                        $success = $this->deleteFile($userFiles[$_GET["file"]]);
                        if ($success) {
                            unset($userFiles[$_GET["file"]]); // remove it from our session and save that info
                            Yii::app()->user->setState($this->stateVariable, $userFiles);
                        }
                    }
                }
            }
            echo json_encode($success);
            return true;
        }
        return false;
    }

}
