<?php

namespace Idocrea8\Image;

use Idocrea8\Image\ImageProcessor;
use Illuminate\Config\Repository;

/**
*
*@author : Tiamiyu waliu
*@website : http://www.iDocrea8.com
*/
class Image
{
    /**
     * Load a ImageProcessor for the uploaded file
     *
     * @param $file
     * @param bool $isUrl
     * @return \iDocrea8\Image\ImageProcessor
     */
    public function load($file, $isUrl = false)
    {
        return new ImageProcessor($file, $isUrl);
    }

    /**
     * Format image url properly
     *
     * @param string $imagePath
     * @param int $size
     * @return string
     */
    public function url($imagePath, $size = 50)
    {
        $url = str_replace('%d', $size, $imagePath);
         if (!file_exists(base_path().'/'.$url)) {
             switch($size) {
                 case 300:
                     $url = str_replace('%d', 200, $imagePath);
                     break;
                 case 960:
                     $url = str_replace('%d', 'original', $imagePath);
                     break;
             }
         }


        return \URL::to($url);
    }

    /**
     * delete image
     *
     * @param string $path
     * @return boolean
     */
    public function delete($path)
    {
        $sizes = \Config::get('image::sizes');
        $basePath = public_path('').'/';
        if (preg_match('#%d#', $path)) {
            foreach($sizes as $size)
            {
                $filePath = $basePath.str_replace('%d', $size, $path);

                if (file_exists($filePath)) {
                    \File::delete($filePath);
                }
            }

            $originalPath = $basePath.str_replace('%d', 'original', $path);
            if (file_exists($originalPath)) {
                \File::delete($originalPath);
            }
        } else {
            $path = $basePath.$path;

            if (file_exists($path)) {
                \File::delete($path);
            }
        }

        return true;
    }
}