<?php

use Illuminate\Database\Seeder;
use App\Article;
use Faker\Factory;
use Intervention\Image;
// use Curl;

class ArticleTableSeeder extends Seeder
{
	protected $faker;
	protected $images;

 	public function __construct()
  	{
	    $options = [
    	  	'key' => '7527655-dc2ae46ea7e73a5696e120e0e',
		  	'q' => 'fire-flowers',
	      	'response_group' => 'high_resolution',
	      	'image_type' => 'photo',
	      	'per_page' => 200,
	      	'editors_choice' => true,
	      	'orientation' => 'horizontal',
	      	'safesearch' => true
	    ];

	    $images = Curl::to('https://pixabay.com/api/?'.http_build_query($options))->get();

	    $this->images = json_decode($images)->hits;
	    $this->faker = Factory::create();
  	}

  	public function generateRandomImage()
  	{
  		$url = $this->images[array_rand($this->images)]->fullHDURL;
  		$image = Image::make($url)->encode('JPG', 80);
  		$name = 'generated-'.uniqid().'.jpg';
  		$path = storage_path('app/public/img/article/');
        File::makeDirectory($storage_path, 0775, true, true);
        $image->save($storage_path.$name);

        return $name;
  	}

  	public function generateTranslations()
	{
	    $translations = [];
	    foreach (config('translatable.locales') as $lang => $language) {
	      	$data = [];
	        data_fill($data, 'title', $this->faker->sentence());
	        data_fill($data, 'content', '<p>'.$this->faker->paragraphs(rand(4, 8), true).'</p> <img src="'.$this->images[array_rand($this->images)]->fullHDURL.'"><p>'.$this->faker->paragraphs(rand(8, 12), true).'" </p>');

	      	data_fill($translations, $lang, $data);
	    }
	    return $translations;
	}



    public function run()
    {
		$user = App\User::all()->pluck('id');
	    
	    foreach (range(1, 20) as $i) {
	    	$article = new Article;
	    	$article->user_id = $user->random();
	    	$article->banner = $this->generateRandomImage();
	    	$article->published = true;
	    	$article->fill($this->generateTranslations());
	    	$article->save();
	    }
    }
}
