<?php

use Illuminate\Database\Seeder;
use App\Article;
use App\Media;

class ChangeArticleImage extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $filePath = public_path('uploads/files/');
        $articlePath = public_path('uploads/image/article/');

        $mediaSlider = Media::where('name', 'Articles')
            ->where('slug', 'articles')
            ->where('type', 0)
            ->where('parent_id', 0)
            ->where('is_deleted', false)
            ->first();

        if (!isset($mediaSlider) || $mediaSlider->id == null) {
            $mediaSlider = Media::create([
                'name'       => 'Articles',
                'slug'       => 'articles',
                'file'       => md5('articles' . rand(1000, 100000)),
                'type'       => 0,
                'parent_id'  => 0,
                'is_deleted' => 0,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        }

        $articles = Article::all();
        foreach ($articles as $article) {
            if ($article->thumbnail != null && $article->thumbnail != "" && file_exists($articlePath . $article->thumbnail)) {
                $this->saveMedia($article->thumbnail, $article->thumbnail, $articlePath, $filePath, $mediaSlider->id);
                $this->toWebp($article->thumbnail);
            }
        }
    }

    public function toWebp($file) {
        $key = "87252hahagawbj";
        $filePath = public_path('uploads/files/');

        $newName = basename($file);
        $newName = str_replace(".jpg" . $key, "", $newName . $key);
        $newName = str_replace(".png" . $key, "", $newName);
        $newName = str_replace(".jpeg" . $key, "", $newName);
        $newName = str_replace(".PNG" . $key, "", $newName);
        $newName = str_replace(".JPG" . $key, "", $newName);
        $newName = str_replace(".JPEG" . $key, "", $newName);
        $newName = str_replace(".gif" . $key, "", $newName);
        $newName .= ".webp";

        ImageCross::make($filePath . $file)->encode('webp', 90)->save($filePath . $newName);
        print "Converted: " . $newName . "\r\n";
    }

    private function saveMedia($fileName, $title, $oldPath, $newPath, $mediaParentId) {
        $imageCross = ImageCross::make($oldPath .  $fileName)->orientate()->save($newPath . $fileName);
        $imgWidth = $imageCross->width();
        $imgHeight = $imageCross->height();
        $imgSize = $imageCross->filesize();
        $fileType = $imageCross->mime();
        $extension = "." . $this->fileExtension($fileName);

        $baseName = trim($title);
        $baseName = str_replace($extension, "", $baseName);
        $baseName = $baseName . $extension;

        $slug = str_replace($extension, "", $fileName);
        $slug = str_replace(" ", "", $slug);
        $slug = str_replace(".", "", $slug);

        $extKey = "223344";
        $countBaseName = 0;
        $checkName = Media::where('is_deleted', 0)->where('parent_id', $mediaParentId)->where('name', $baseName)->count();
        $firstBaseName = str_replace($extension . $extKey, "", $baseName . $extKey);
        while ($checkName > 0) {
            $countBaseName += 1;
            $baseName = $firstBaseName . " (" . $countBaseName . ")" . $extension;
            $checkName = Media::where('is_deleted', 0)->where('parent_id', $mediaParentId)->where('name', $baseName)->count();
        }

        Media::create([
            'name'       => $baseName,
            'slug'       => $slug,
            'file'       => $fileName,
            'file_type'  => $fileType,
            'extension'  => $extension,
            'size'       => $this->formatBytes($imgSize),
            'width'      => $imgWidth,
            'height'     => $imgHeight,
            'type'       => 1,
            'parent_id'  => $mediaParentId,
            'is_deleted' => 0,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        print "Media Saved: " . $baseName . "\r\n";
    }

    private function formatBytes($bytes, $precision = 2)
    {
        $units = array('B', 'Kb', 'MB', 'GB', 'TB');
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1024, $pow);

        return round($bytes, $precision) . '' . $units[$pow];
    }

    private function fileExtension($s)
    {
        $n = strrpos($s, ".");
        return ($n === false) ? "" : substr($s, $n + 1);
    }
}
