<?php

namespace App\Http\Controllers;

use App\Marker;
use App\Photo;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class PhotosController extends Controller
{
    /**
     * Generate image thumbnail.
     *
     * @param $photo - files from Request $request
     * @param $markerId - ID of marker which thumbnail should belongs to
     * @return $filename - name of generated thumbnail file
     */
    private function generateThumbnail($photo, $markerId)
    {
      //generate thumbnail
      $thumbnail = Image::make($photo)->widen(150)->encode('jpg', 90);
      // calculate md5 hash of encoded image
      $filename = $photo->getClientOriginalName();
      Storage::put('photos/'.$markerId.'/thumbnails/'.$filename, $thumbnail);

      return $filename;
    }

    /**
     * Save photos from request to disk storage and create DB records for them.
     *
     * @param $photos - Array of files
     * @param $markerId - ID of marker which thumbnail should belongs to
     */
    private function createPhotos($photos, $markerId)
    {
      foreach ($photos as $photo) {
          $filename = $photo->storeAs('photos/'.$markerId, $photo->getClientOriginalName());
          $filename = basename($filename);

          $thumbnail = $this->generateThumbnail($photo, $markerId);

          Photo::create([
              'marker_id' => $markerId,
              'src' => $filename,
              'thumbnail' => $thumbnail
          ]);
      }
    }

  /**
   * @apiDefine Header
   * @apiHeader {String} Authorization Bearer + token
   * @apiHeaderExample Authorization header example
   * Authorization: Bearer eyJ0eXAiO.iJKV1QiLCJhb.GciOiJIUzI1NiJ9
   */

   /**
    * @apiDefine JWTErrors
    * @apiError TokenNotProvided Token not provided.
    * @apiErrorExample TokenNotProvided response:
    *     HTTP/1.1 401 Unauthorized
    *     {
    *       "error": "Token not provided."
    *     }
    *
    * @apiError ExpiredToken Provided token is expired.
    * @apiErrorExample ExpiredToken response:
    *     HTTP/1.1 400 Bad Request
    *     {
    *       "error": "Provided token is expired."
    *     }
    *
    * @apiError DecodingError An error while decoding token.
    * @apiErrorExample DecodingError response:
    *     HTTP/1.1 400 Bad Request
    *     {
    *       "error": "An error while decoding token."
    *     }
    */

    /**
     * @api {post} /photos Create New Photo
     * @apiVersion 1.0.0
     * @apiName CreateNewPhoto
     * @apiGroup Photo
     * @apiPermission authenticated
     *
     * @apiUse Header
     *
     * @apiDescription Request params must be sent as <strong>form-data</strong>.
     *
     * @apiParam {String{..50}} marker_id ID of a marker which photo belong to.
     * @apiParam {Array} photos Array of files (photos).
     *
     * @apiSuccess {String} success Success message.
     * @apiSuccess {Array} photos Array of photos attached to marker.
     *
     * @apiSuccessExample Success Response:
     *     HTTP/1.1 200 OK
     *     {
     *       "success": "Upload was successfull.",
     *       "photos": [
     *         {
     *           "id": 1,
     *           "marker_id": 8,
     *           "src": "Studna_JP_358.jpg",
     *           "thumbnail": "Studna_JP_358.jpg"
     *         }
     *       ]
     *     }
     *
     * @apiUse JWTErrors
     */
    public function create(Request $request)
    {
      //validation rules
      $rules = ['marker_id' => 'required|numeric'];

      $photos = count($request->photos);

      foreach(range(0, $photos) as $index) {
        $rules['photos.' . $index] = 'image|mimes:jpg,jpeg,png|max:5120';
      }

      //validate request
      $this->validate($request, $rules);

      $marker = Marker::findOrFail($request->marker_id);

      $this->createPhotos($request->photos, $request->marker_id);

      $photos = Marker::find($request->marker_id)->photos;

      return response()->json([
        'success' => 'Upload was successfull.',
        'photos' => $photos
      ], 200);
    }

    /**
     * @api {delete} /photos/:id Delete Photo
     * @apiVersion 1.0.0
     * @apiName DeletePhoto
     * @apiGroup Photo
     * @apiPermission authenticated
     *
     * @apiUse Header
     *
     * @apiParam {Number} id Photos unique ID.
     *
     * @apiSuccess {String} success Success message.
     *
     * @apiSuccessExample Success Response:
     *     HTTP/1.1 202 OK
     *     {
     *       "success": "Photo was successfully deleted."
     *     }
     *
     * @apiUse JWTErrors
     */
    public function delete($id)
    {
        $photo = Photo::findOrFail($id);
        $markerId = $photo->marker_id;
        $image = $photo->src;
        $thumbnail = $photo->thumbnail;

        $photo->delete();

        //delete files from disk
        Storage::delete('/photos/'.$markerId.'/'.$image);
        Storage::delete('/photos/'.$markerId.'/thumbnails/'.$thumbnail);

        return response()->json(["success" => "Photo was successfully deleted."], 202);
    }
}
