<?php
namespace App\Transformer\Home;

use Vinkla\Hashids\Facades\Hashids;

class HomeTransformer
{
    public function newBuildHomeList($data): array
    {
        return [
            'meta'              => getMeta($data['favorite_books']),
            'banners'           => $this->newEachBanner($data['banners']),
            'feature_books'     => $this->newEachFeatureBooks($data['feature_books']),
            'favorite_books'    => $this->newEachFavoriteBooks($data['favorite_books']->items()),
            'current_book'      => $this->newEachCurrentBook($data['current_book']),
            'book_gender'       =>  $data['book_gender'],
        ];
    }

    private function newEachBanner($list): array
    {
        $result = [];
        if (empty($list)) return $result;

        foreach ($list as $item) {
            $result[] = [
                'bid'               => Hashids::encode(getProp($item, 'id')),
                'book_name'         => getProp($item, 'name'),
                'cover'             => addPrefix(getProp($item, 'cover')),
                'intro'             => filterIntro(getProp($item, 'intro')),
            ];
        }

        return $result;
    }

    private function newEachFeatureBooks($list): array
    {
        $result = [];
        if (empty($list)) return $result;

        foreach ($list as $item) {
            $result[] = [
                'bid'               => Hashids::encode(getProp($item, 'id')),
                'book_name'         => getProp($item, 'name'),
                'cover'             => addPrefix(getProp($item, 'cover')),
                'intro'             => filterIntro(getProp($item, 'intro')),
                'category_name'     => getProp($item, 'category_name') ? getProp($item, 'category_name') : '其他',
                'gender'            => getProp($item, 'gender'),
            ];
        }

        return $result;
    }

    private function newEachFavoriteBooks($list): array
    {
        $result = [];
        if (empty($list)) return $result;

        foreach ($list as $item) {
            $result[] = [
                'bid'               => Hashids::encode(getProp($item, 'id')),
                'book_name'         => getProp($item, 'name'),
                'intro'             => filterIntro(getProp($item, 'intro')),
                'cover'             => addPrefix(getProp($item, 'cover')),
                'author'            => getProp($item, 'author'),
                'category_name'     => getProp($item, 'category_name') ? getProp($item, 'category_name') : '其他',
                'gender'            => getProp($item, 'gender'),
            ];
        }
        return $result;
    }

    private function newEachCurrentBook($list): array
    {

        if (empty($list)) {
            return [];
        }

        $list = (array)$list;
        $list['bid'] = Hashids::encode($list['bid']);

        return $list;
    }
}
