<?php
/**
 * Controller for photos
 *
 * This file is part of Zoph.
 *
 * Zoph is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Zoph is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with Zoph; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @package Zoph
 * @author Jeroen Roos
 */

namespace photos;

use file\archive;
use conf\conf;
use generic\controller as genericController;
use photo;
use photo\collection;
use photos\view\display;
use photos\view\download;
use photos\view\edit;
use photos\view\zipfile;
use photos\view\prepare;
use user;
use web\request;

use photoNotAccessibleSecurityException;

/**
 * Controller for photos
 */
class controller extends genericController {

    protected static $viewDisplay   = view\display::class;
    protected static $viewEdit      = view\edit::class;
    protected static $viewDownload  = view\download::class;
    protected static $viewPrepare   = view\prepare::class;
    protected static $viewZipfile   = view\zipfile::class;


    /** @var array Actions that can be used in this controller
      * Actions for download *download* -> *prepare* -> *zipfile*
      * */
    protected $actions = array("display", "download", "edit", "prepare", "update", "search", "zipfile");

    /** @var string Where to redirect after actions */
    public $redirect="photos.php";

    /** @var int total number of photos return by the query */
    public $photocount = 0;

    /** @var params holds params object, containing params parameters
                       such as sort order, number of rows and columns */
    private $params;

    /** @var array holds array of photo_ids that are in the user's lightbox */
    private $lbPhotos = array();

    /** @var photo\collection holds collection of photos to work with */
    private $collection;

    /** @var photo\collection holds collection of photos to show */
    private $toDisplay;

    /**
     * Create a controller using a web request
     * @param request request
     */
    public function __construct(request $request) {
        parent::__construct($request);
        $user=user::getCurrent();

        $this->params = new params($request);

        $this->lbPhotos = $this->params->getLightBox();

        $this->collection = collection::createFromRequest($request);
        $this->toDisplay = $this->collection->subset(
            $this->params->offset, $this->params->cells);

        if (!conf::get("feature.download") || (!$user->get("download") && !$user->isAdmin())) {
            $this->actions = array("display", "edit", "update", "search");
        }

        $this->doAction();

    }

   /**
    * Get the photo collection for the current request
    * @return photo\collection
    */
    public function getPhotos() {
        return $this->collection;
    }

   /**
    * Get the photo collection that should be displayed
    * this is different from @see getPhotos() as this takes paging
    * into account, so it will usually only return a subset of photos
    * @return photo\collection
    */
    public function getDisplay() {
        return $this->toDisplay;
    }

   /**
    * Get the photo_ids that are in the user's lightbox
    * @return array
    */
    public function getLightbox() {
        return $this->lbPhotos;
    }

   /**
    * Get a params object, containing various variables to do with the interface
    * such as sort order, number of columns, rows, etc.
    * @return photos\params Params object
    */
    public function getParams() {
        return $this->params;
    }

    /**
     * Do action 'display'
     */
    public function actionDisplay() {
        $this->view=new static::$viewDisplay($this->request, $this->getParams());
        $this->view->setPhotos($this->getPhotos());
        $this->view->setDisplay($this->getDisplay());
        $this->view->setLightBox($this->getLightbox());
        $style = $this->getParams()->getStyle();
        if ($style) {
            $this->view->setStyle($style);
        }
    }

    /**
     * Do action 'edit'
     */
    public function actionEdit() {
        $this->view=new static::$viewEdit($this->request, $this->getParams());
        $this->view->setPhotos($this->getPhotos());
        $this->view->setDisplay($this->getDisplay());
    }

    /**
     * Do action 'download'
     * This displays the form for the download, the actual download is handled by @see actionPrepare @see actionZipfile()
     */
    public function actionDownload() {
        $this->view=new static::$viewDownload($this->request, $this->getParams());
        $this->view->setPhotos($this->getPhotos());
        $this->view->setDisplay($this->getDisplay());
    }

    /**
     * Do action 'prepare'
     * This prapares the download of the ZIP file, the actual download is handled by @see actionZipfile
     */
    public function actionPrepare() {
        $maxfiles = (int) ($this->request["_maxfiles"] ?? 200);
        $maxsize = (int) ($this->request["_maxsize"] ?? -1);
        $filenum=(int) ($this->request["_filenum"] ?? 1);
        $index=(bool) ($this->request["_index"] ?? false);

        $filename=$this->request["_filename"] ?? "zoph";

        if (!preg_match("/^[a-zA-Z0-9_-]+$/", $filename)) {
            throw new filenameException("Invalid filename");
        }

        $zip = new archive(archive::ZIP, $filename, $filenum);
        $zip->setMaxSize($maxsize);
        if ($index) {
            $zip->setIndex(floor(log10(sizeof($this->getDisplay()))) + 1, $this->params->offset);
        }

        if (sizeof($this->getDisplay()) > $maxfiles) {
            $photos = $this->getDisplay()->subset(0, $maxfiles);
        } else {
            $photos = $this->getDisplay();
        }

        $added=$zip->addPhotos($photos);

        $this->view=new static::$viewPrepare($this->request, $this->getParams());
        $this->view->setPhotos($this->getPhotos());
        $this->view->setDisplay($photos);
        $this->view->setFile($filename, $filenum, $added);
    }

    /**
     * Do action 'zipfile'
     * This performs the actual download
     */
    public function actionZipfile() {
        $this->view=new static::$viewZipfile($this->request, $this->getParams());
    }

    /**
     * Do action 'update'
     */
    public function actionUpdate() {
        $this->setFields();
        self::actionEdit();
    }

    /**
     * Do action 'search'
     */
    public function actionSearch() {
        $this->actionDisplay();
    }

    /**
     * Get View
     * @return photo\view
     */
    public function getView() {
        return $this->view;
    }

    /**
     * Set values from 'all photos' section
     */
    private function setFields() {
        $user = user::getCurrent();
        $request = $this->request;

        foreach ($this->getDisplay() as $photo) {
            $action = "";
            if (isset($request["_action__" . $photo->getId()])) {
                $action = $request["_action__" . $photo->getId()];
            }

            if ($photo->isWritableBy($user) && $action == "update") {
                $this->setFieldsForPhoto($photo);
            } else if ($photo->isWritableBy($user) && $action == "delete") {
                $photo->delete();
            }
        }
    }

    /**
     * Set fields for photo
     * This takes the variables, passed in the request and applies them to a photo
     * @param photo Photo
     */
    private function setFieldsForPhoto(photo $photo) {
        $request = $this->request;
        $photo->lookup();

        $vars = $request->getRequestVars();
        $vars = $this->unsetInternalFields($vars, "__all");

        $vars = $this->unsetInternalFields($vars, "__" . $photo->getId());

        $rating = null;
        if ($request['_overwrite']) {
            $this->setPhotoFields($vars, $photo, '__' . $photo->getId());
            $this->setPhotoFields($vars, $photo, '__all');

            $rating = $request["_rating__" . $photo->getId()];
            if ($request["_rating__all"]) {
                $rating = $request["_rating__all"];
            }
        } else {
            $this->setPhotoFields($vars, $photo, '__all');
            $this->setPhotoFields($vars, $photo, '__' . $photo->getId());
            $rating = $request["_rating__all"];
            if ($request["_rating__" . $photo->getId()]) {
                $rating = $request["_rating__" . $photo->getId()];
            }
        }

        if ($rating != "0"  && conf::get("feature.rating")) {
            $photo->rate($rating);
        }
    }

    /**
     * Set submitted values on photo
     */
    private function setPhotoFields(array $vars, $photo, $suffix) {
        $photo->setFields($vars, '__', $suffix, false);
        $photo->update();
        $photo->updateRelations($vars, $suffix);
    }

    /**
     * Unset internal fields
     * Removes certain fields from the variables array, to prevent them from being applied to photos
     * these are fields that are used by e.g. the autocomplete feature
     * @param array variables to process
     * @param string suffix to add to internal fields
     * @return array cleaned up variables
     */
    private function unsetInternalFields(array $vars, string $suffix) {
        $internal = array("___location_id", "___photographer_id", "__album", "__category", "__person");

        foreach ($internal as $field) {
            unset($vars[$field . $suffix]);
        }

        return $vars;
    }

}
