<?php

namespace App\Http\Controllers\Frontend\Board;

use App\Http\Controllers\Controller;
use App\Models\Boards\UserUploadedImage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class UserUploadedImageController extends Controller
{
    public function store(Request $request)
    {

        $image = $request->file('file');
       //    dd($image);
        $type = strtolower($image->getClientOriginalExtension());
        $originalname = $image->getClientOriginalName();
        $filename = $image->getFilename();
        $path = $image->getPath();
        $size = $image->getSize();
        // is this an allowed type?
        if (!in_array($type, ['jpg', 'jpeg', 'png'])) {
            throw new GeneralException('You must supply a jpg or png image.');
        }
        $img = Image::make($image);
        //dd($img);
        // get the md5 hash of the contents. This allows for different files with the same name in teh same directory...
        $md5name = md5(file_get_contents($path . DIRECTORY_SEPARATOR . $filename));

        // Intervention image
     //   $img = Image::make($image);

        // fix any weird mobile orientation issues
        $img->orientate();

//        // Make the image a sensible size
        $img->resize(($img->getHeight() > $img->getWidth()) ? 640 : 960, null , function ($constraint) {
            $constraint->aspectRatio();
        });
        // save with the UUID as a filename
        $img->save(Storage::disk('user_uploaded_media')->path('/') . $md5name);
        $media = UserUploadedImage::updateOrCreate(['name' => $originalname,
            'size' => $size,
            'type'=>$type,
            'location' => $md5name,
            'path' => Storage::disk('user_uploaded_media')->path('/') . $md5name,
            'user_id' => auth()->user()->id]);

        // $user->avatar_location = 'avatars/' . $user->uuid . '.jpg';
        return array(
            'id' => $media->id,
            'location' => route('frontend.board.displayusermedia', $media->id),
            'thumb' => route('frontend.board.displayusermediathumb', $media->id),
        );

    }

    // Get by page. We may be needing tags later, so I'll leave the stuff in there to make that happen when we need
    public function get_by_page(Request $request)
    {
        $returnVal = [];
        $returnVal['items'] = UserUploadedImage::where(['user_id' => auth()->user()->id])->skip(($request['page'] - 1) * 20)->take(($request['page']) * 20)->get();
//        if ($request['tags']) {
//
//            $returnVal['items'] = Shape::withTags($request['tags'])->skip(($request['page'] - 1) * 20)->take(($request['page']) * 20)->get()->makeHidden('colourways');
//            $returnVal['count'] = Shape::withTags($request['tags'])->count();
//        } else {
//
//            $returnVal['items'] = Shape::skip(($request['page'] - 1) * 20)->take(($request['page']) * 20)->get()->makeHidden('colourways');
//            $returnVal['count'] = Shape::count();
//        }
        return $returnVal;
    }

    // shows the raw file. If it's an image, display it, if anything else, show an icon.
    public function display($id)
    {
//dd('hi');
        $media = UserUploadedImage::findOrFail($id);
        // dd($media);

        switch (strtolower($media->type)) {
            case 'jpg':
                $location = $media->location;
                $content_typestr = 'image/jpeg';
                break;
            case 'png':
                $location = $media->location;
                $content_typestr = 'image/png';
                break;
            case 'bmp':
                $location = $media->location;
                $content_typestr = 'image/bmp';
                break;

            default:
                $location = '/unknown_img.png';
                $content_typestr = 'image/png';
                break;
        }
        $file = Storage::disk('user_uploaded_media')->get($location);
        // resize image

        $response = new \Illuminate\Http\Response($file, '200');
        $response->header("Content-Type", $content_typestr);
        return $response;
    }

    // display a thumbnail from an id
    public function thumb($id)
    {

        $media = UserUploadedImage::findOrFail($id);

        switch (strtolower($media->type)) {
            case 'jpg':
            case 'jpeg':
            case 'png':
            case 'bmp':
            $location = $media->location;
                $file = Storage::disk('user_uploaded_media')->get($location);
                break;

            default:
                $file = Storage::get('/public/unknown.png');
                break;
        }
        $image = Image::make($file);
        // get image height and width
        $origheight = $image->height();
        $origwidth = $image->width();

        // work out the ratio
        $ratio = ($origheight / $origwidth);
// work out size
        $size = array(($ratio < 0 ? (100 * $ratio) : 100), ($ratio < 0 ? 100 : (100 * $ratio)));
        // resize, dump out
        //return $image->resize($size[0], $size[1])->response();
        return $image->fit(100,100)->response();
    }

    public function destroy($id)
    {

        $status = UserUploadedImage::destroy($id);

        $response = array(
            'status' => ($status>0)?0:1,
            //'status' => 0,
        );
        return $response;

    }
}
