<?php

namespace App\Http\Resources;

use App\Topic;
use Illuminate\Http\Resources\Json\JsonResource;
use ImageCross;

class TopicResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'            => $this->id,
            'code'          => $this->code,
            'title'         => $this->title,
            'thumbnail'     => $this->thumbnail,
            'author'        => $this->author,
            'total_comment' => $this->total_comment,
            'comment'       => array_map(
                function ($comment) {
                    return [
                        'id'               => $comment['id'],
                        'idx'              => $comment['idx'],
                        'content'          => $comment['content'],
                        'image'            => $comment['image'],
                        'like'             => $comment['like'],
                        'dislike'          => $comment['dislike'],
                        'author'           => $comment['author'],
                        'is_anonymous'     => $comment['is_anonymous'],
                        'is_show_id'       => $comment['is_show_id'],
                        'is_allow_comment' => $comment['is_allow_comment'],
                        'commentCount'     => $comment['commentCount'],
                        'created_at'       => $comment['created_at'],
                    ];
                },
                $this->comment->toArray()
            ),
            'seo_robots'       => $this->seo_robots,
            'seo_title'        => $this->seo_title,
            'seo_description'  => $this->seo_description,
            'seo_keywords'     => $this->seo_keywords,
            'created_at'    => date('Y-m-d H:i:s', strtotime($this->created_at)),
        ];
    }

    public static function generateCode($length = 6)
    {
        do {
            $key = strtoupper(substr(str_shuffle("010123401234501234567896789501234567896789234567890001234560123456789789123456789123456789012345"), 0, $length));
            $check = Topic::where('code', $key)->count();
        } while ($check > 0);

        return $key;
    }

    public static function createThumb($file, $width = 60, $height = 60)
    {
        try {
            $filePath = public_path('uploads/image/topic');
            $fileName = md5(date('YmdHis') . rand(1, 9999)) . '.jpg';
            $imgCross = ImageCross::make($file)->orientate()->save($filePath . '/' . $fileName);
            $imgCross->resize(60, 60, function ($constraint) {
                $constraint->aspectRatio();
                $constraint->upsize();
            })->save($filePath . '/thumbnail_60x60/' . $fileName);
            return $fileName;
        } catch (\Exception $exception) {
            return "";
        }
    }
}
