<?php
namespace App\Database\Seeds;

use Faker\Factory;
use Curl;
use Image;
use File;

class FactoryHelper
{
  protected $image, $faker;

  function __construct()
  {
    $options = [
      'client_id' => 'c646c5ff224124c02f9e291daec43b739cf738fe8383ee5fb255f830c31c4fed',
      'query' => 'food',
      'per_page' => 30
    ];
    $image = Curl::to('https://api.unsplash.com/search/photos?'.http_build_query($options))->get();
    $this->images = json_decode($image)->results;
    $this->faker = Factory::create();
  }

  /**
   * Generate random url
   */
  public function generateRandomUrl()
  {
    return $this->images[array_rand($this->images)]->urls->regular;
  }

  /**
   * Save image from generated url to storage
   */
  public function generateRandomImage($prefix, $path)
  {
    $image = Image::make($this->generateRandomUrl())->encode('jpg', 80);
    $name = $prefix.'__'.uniqid().'__80.jpg';
    $storage_path = storage_path('app/public/'.$path);
    File::makeDirectory($storage_path, 0775, true, true);
    $image->save($storage_path.$name);

    return $name;
  }

}
