<?php

namespace App\Http\Controllers;

use App\Models\VoiceModel;
use Illuminate\Http\Request;

class Voice extends Controller
{
    public function store(Request $request)
    {
        $this->validate($request, [
            'content' => 'required',
            'type' => 'required'
        ]);
        $model = new VoiceModel();
        $voice = $model->fill([
            'content' => $request->input('content'),
            'type' => $request->input('type')
        ]);
        if ($voice->save()) {
            return array(
                'code' => 200,
                'message' => 'success',
                'data' => [
                    'voice_id' => $voice->id
                ],
            );
        } else {
            return array(
                'code' => 505,
                'message' => '数据库错误'
            );
        }
    }

    /**
     * @param  Request  $request
     * @param  int  $voice_id
     * @return array
     * @api {Post} /api/voice/:voice_id/update 更新语音独白
     * @apiName UpdateVoiceRead
     * @apiGroup Voice
     *
     * @apiParam {String} content 独白内容
     *
     * @apiSucsess {json} Success-Response:
     *  HTTP/1.1 200 OK
     *  {
     *      "code": 200,
     *      "message": "success"
     *  }
     */
    public function update(Request $request, int $voice_id)
    {
        $model = new VoiceModel();
        $read = $model->find($voice_id);
        if (collect($read)->isEmpty()) {
            return array(
                'code' => 101,
                'message' => '参数错误'
            );
        }
        $read->content = $request->input('content');
        if ($read->save()) {
            return array(
                'code' => 200,
                'message' => 'success',
                'data' => [
                    'id' => $read->id
                ],
            );
        } else {
            return array(
                'code' => 505,
                'message' => '数据库错误'
            );
        }
    }

    /**
     * @param  string  $type
     * @return array
     * @api {Get} /api/voice/:type 获取某个类型的独白
     * @apiName GetVoicesByType
     * @apiGroup Voice
     *
     * @apiParam {String} type 类型
     *
     * @apiSucsess {json} Success-Response:
     *  HTTP/1.1 200 OK
     *  {
     *      "code": 200,
     *      "message": "success"
     *  }
     */
    public function get(string $type)
    {
        $model = new VoiceModel();
        $reads = $model->where('type', $type)->get();
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $reads
        );
    }
}
