<?php namespace JasonWilliams\ImgCache\Classes;

/*
        Find a faster way of returning in the event of a 404
*/

use October\Rain\Network\Http;
use October\Rain\Filesystem\Filesystem;

class Image
{
  protected $file;
  protected $folder;
  protected $urlbase;
  protected $imgurl;
  protected $filename;
  protected $found = false;

  public function __construct($url)
  {
    $this->imgurl = $url;
    $this->folder = base_path(substr(config('cms.storage.media.path'), 1)).'/external/';
    $this->urlbase = config('cms.storage.media.path').'/external/';
    $this->filename = md5($url).'.jpg';

    $fs = new Filesystem;

    if($fs->existsInsensitive($this->folder.$this->filename))
    {
      $this->found = true;
      $this->imgurl = $this->urlbase.$this->filename;
      return;
    }

    $req = new Http();
    $img = $req->get($url, [
      'CURLOPT_CONNECTTIMEOUT' => 1
    ]);

    if ($img->code !== 200) $this->imgurl = '/plugins/jasonwilliams/imgcache/assets/images/notfound.png';
    else {
      $this->found = true;
      $fs->put($this->folder.$this->filename, $img);
      $this->imgurl = $this->urlbase.$this->filename;
    }
  }

  public function __toString()
  {
    return $this->imgurl;
  }
}