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

namespace App\Resps\Eloquents;

use App\Resps\Interfaces\Image as ImageInterface;
use App\Resps\Interfaces\Upload as UploadInterface;
use Illuminate\Support\Facades\Auth;

class Upload implements UploadInterface
{
    private $image;

    public function __construct(ImageInterface $image)
    {
        $this->image = $image;
    }

    public function base64upload(array $params)
    {
        if (!$base64_code = is_or($params, 'base64_code')) {
            return ['code' => 401];
        }
        $name = is_or($params, 'name') ?: 'no_name';
        $data = explode(',', $base64_code);
        if (!preg_match('/^data:image\/(\w+?);base64/', $data[0], $m)) {
            return ['code' => 402];
        }
        $name = (microtime(1) * 10000) . '_' . $name . '.' . $m[1];
        $inner_path = 'static/upload/' . Auth::id() . '/' . Date('Y/m/d');
        $path = public_path($inner_path);
        if (!$this->checkUploadDir($path)) {
            return ['code' => 403];
        }
        file_put_contents($path . '/' . $name, base64_decode($data[1]));
        if (!file_exists($path . '/' . $name)) {
            return ['code' => 404];
        }
        $insertData = [
            'name' => explode('.', $name)[0],
            'path' => '/' . $inner_path . '/' . $name,
            'desc' => '',
            'size' => @filesize($path . '/' . $name),
            'creator_id' => Auth::id(),
            'mender_id' => Auth::id(),
        ];

        return $this->image->create($insertData);
    }

    private function checkUploadDir($path)
    {
        is_dir($path) ? true : @mkdir($path, 0775, true);
        return is_dir($path);
    }
}