<?php
/**
 * Created by PhpStorm.
 * User: glsy
 * Date: 2018/6/28
 * Time: 下午2:20
 */

namespace App\Resps\Eloquents;

use App\Models\Image as ImageModel;
use App\Resps\Interfaces\Image as ImageInterface;
use Illuminate\Support\Facades\Auth;

class Image implements ImageInterface
{
    public function show($id)
    {
        //
    }

    public function create(array $params)
    {
        $insertData = [];
        if (!$insertData['name'] = is_or($params, 'name')) {
            return ['code' => 418];
        }
        if (!$insertData['path'] = is_or($params, 'path')) {
            return ['code' => 419];
        }
        if (!file_exists(public_path($insertData['path']))) {
            return ['code' => 420];
        }
        $insertData['desc'] = is_or($params, 'desc');
        $insertData['size'] = is_or($params, 'size');
        $insertData['creator_id'] = $insertData['mender_id'] = Auth::id();

        try {
            $image = ImageModel::create($insertData);
            return ['code' => 0, 'data' => $image->toArray()];
        } catch (\Exception $e) {
            return ['code' => 415];
        }
    }

    public function update($id, array $params)
    {
        //

    }

    public function destroy(array $ids)
    {
        if (empty($ids) || empty($images = ImageModel::whereIn('id', $ids)->get()->toArray())) {
            return ['code' => 416];
        }
        $image_ids = array_column($images, 'id');
        $image_path = array_filter(array_column($images, 'path'), function ($y) {
            return strpos($y, '/static/img/default/') === false;
        });
        try {
            if (ImageModel::whereIn('id', $image_ids)->delete()) {
                array_map(function ($y) {
                    $realpath = public_path($y);
                    file_exists($realpath) && @unlink($realpath);
                }, $image_path);
            }
            return ['code' => 0];
        } catch (\Exception $e) {
            return ['code' => 417];
        }
    }
}