<?php
namespace Zeedhi\ZhuLog\Logger\Processor;

class SkipFilesProcessor extends Processor {

    /** @var array */
    protected $fileRoutes = [];

    /**
     * Constructor...
     * 
     * @param array $fileRoutes
     */
    public function __construct(array $fileRoutes) {
        $this->fileRoutes = $fileRoutes;
    }

    /**
     * Remove base64 files data from log
     * {@inheritDoc}
     */
    public function processRequest(array $request, string $route, string $method) : array {
        if (isset($this->fileRoutes[$route])) {
            $request = $this->removeFileFields($request, $this->fileRoutes[$route]['fileField']);
        }

        return $request;
    }

    /**
     * {@inheritDoc}
     */
    public function processResponse(array $response) : array {
        return $response;
    }

    /**
     * {@inheritDoc}
     */
    public function processException(string $message) : array {
        return ['error' => $message];
    }

    /**
     * Removes the file fields.
     * 
     * @param array $request
     * @param string $field
     * 
     * @return array
     */
    protected function removeFileFields(array $request, string $field) : array {
        if (isset($request['row'])) {
            $request['row'] = $this->removeFieldFromRow($request['row'], $field);
        } else if (isset($request['dataset'])) {
            $request['dataset'] = $this->removeFieldFromRows($request['dataset'], $field);
        }

        return $request;
    }

    /**
     * Removes fields from rows.
     * 
     * @param array $rows
     * @param string $field
     * 
     * @return array
     */
    protected function removeFieldFromRows(array $rows, string $field) : array {
        return array_map(function($row) use ($field) {
            return $this->removeFieldFromRow($row, $field);
        }, $rows);
    }

    /**
     * Remove field from row.
     * 
     * @param array $row
     * @param string $field
     * 
     * @return array
     */
    protected function removeFieldFromRow(array $row, string $field) : array {
        if (!empty($row[$field])) {
            $row[$field] = array_map(function($file) {
                unset($file['b64File']);
                return $file;
            }, $row[$field]);
        }

        return $row;
    }
}