<?php

namespace App\Http\Controllers\Frontend\Graphics;

use App\Http\Controllers\Controller;
use App\Models\Graphics\BackgroundImage;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;
use App\Exceptions\GeneralException;

class BackgroundImageController 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.');
            return ['status'=>400, "msg"=>'You must supply a jpg or png image.','type'=>$type];
        }

        // 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();
        });
//        // crop to square
//        $img->crop(200, 200);

        // save with the UUID as a filename
        $img->save(Storage::disk('user_uploaded_media')->path('/') . $md5name);
        $media = BackgroundImage::updateOrCreate(['name' => $originalname,
            'size' => $size,
            'type' => $type,
            'location' => $md5name,
            'path' => Storage::disk('user_uploaded_media')->path('/') . $md5name,
            'user_id' => auth()->user()->id,
            'public'=> '1'
           ]);
        // $user->avatar_location = 'avatars/' . $user->uuid . '.jpg';
        return array(
            'status'=>200,
            'id' => $media->id,
            'location' => $media->path(),
            'type' => 'background'
           // 'thumb' => route('frontend.board.displayusermediathumb', $media->id),
        );
    }

//    Fakies store for user background images
    public function fakiestore(Request $request){
        return array(
            'status'=>200,
        );
    }

    public function thumb($id)
    {
        $media = BackgroundImage::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 update(Request $request)
    {

        // get the entry and the old path
        $entry = BackgroundImage::find($request['id']);
        $oldpath = $entry->path;

        $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.');
        }

        // 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();
        });
//        // crop to square
//        $img->crop(200, 200);

        // save with the UUID as a filename
        $img->save(Storage::disk('user_uploaded_media')->path('/') . $md5name);
        $media = BackgroundImage::updateOrCreate(['id' => $entry->id], ['name' => $originalname,
            'size' => $size,
            'type' => $type,
            'location' => $md5name,
            'path' => Storage::disk('user_uploaded_media')->path('/') . $md5name,
            'user_id' => auth()->user()->id,
            'public' => '1']);

        // delete the old image
        Storage::delete($oldpath);
        // $user->avatar_location = 'avatars/' . $user->uuid . '.jpg';
        return array(
            'id' => $media->id,
            'location' => $media->path(),
            //'thumb' => route('frontend.board.backgrounds', $media->id),
        );

    }

    public function index(Request $request)
    {

        $images = BackgroundImage::all();

        return view('backend.backgrounds.index')
            ->with('images', $images);
    }

    public function create(Request $request)
    {
//        return view('backend.backgrounds.create');
    }

    public function display($id)
    {
        $media = BackgroundImage::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;
    }

    public function show($id)
    {

        $media = BackgroundImage::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;
    }

    public function edit(Request $request, $id)
    {
        $clipart = BackgroundImage::find($id);
        return view('backend.backgrounds.edit')
            ->with('background', $clipart);
    }

    public function destroy(Request $request, BackgroundImage $clipart)
    {
        // clean up colourways
        // clean up tags
        // delete clipart
        BackgroundImage::find($clipart->id)->delete();
        //$this->userRepository->deleteById($user->id);

        //event(new UserDeleted($user));

        return redirect()->route('backend.backgrounds.index')->withFlashSuccess('Image deleted');
    }

}
