<?php

namespace App\Http\Controllers;

use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use KzykHys\FrontMatter\Document;
use KzykHys\FrontMatter\FrontMatter;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

class PageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function index(Request $request)
    {
        $folder = sprintf('%s/%s', storage_path('app/pages'), Auth::user()->getAuthIdentifier());
        if (!file_exists($folder)) {
            mkdir($folder);
            $request->session()->flash('status', 'Dossier crée !');
        }

        //https://itnext.io/laravel-the-mysterious-ordered-uuid-29e7500b4f8
        $pages = array_reverse(array_map(static function ($page_path) use ($request) {
            try {
                return [
                    'id'   => explode('.', basename($page_path))[0],
                    'date' => DateTime::createFromFormat(
                        'U',
                        substr(hexdec(implode(array_slice(explode('-', basename($page_path)), 0, 2))), 0, 10)
                    )->format('d/m/Y H:i:s'),
                ];
            } catch (\Exception $e) {
                $request->session()->flash('status', 'Date ?');

                return null;
            }
        }, Storage::disk('pages')->files(Auth::user()->getAuthIdentifier())));

        $user = Auth::user();

        return view('pages.index', [
            'checkword' => $user->checkword,
            'pages'     => $pages,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $input = $request->all();
        $uuid = Str::orderedUuid();
        $document = new Document();
        $document->setContent($input['text']);
        unset($input['text']);
        unset($input['_token']);
        $document->setConfig(array_merge($input, [
            'date' => (new DateTime())->format('Ymd His'),
        ]));

        return response()->json([
            'success'   => Storage::disk('pages')->put(sprintf('%s/%s.md', Auth::user()->getAuthIdentifier(), $uuid), FrontMatter::dump($document)),
            'uuid'      => $uuid,
            'date'      => $document->getConfig()['date'],
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param string $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $file_path = sprintf('%s/%s.md', Auth::user()->getAuthIdentifier(), $id);
        if (!Storage::disk('pages')->exists($file_path)) {
            throw new FileNotFoundException('Cette page n\'existe pas.');
        }
        $document = FrontMatter::parse(Storage::disk('pages')->get($file_path));
        if (null === $document) {
            return response()->json([]); // FIX ME
        }
        $json = [
            'metadata' => $document->getConfig(),
            'content'   => $document->getContent(),
        ];

        return response()->json($json);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        throw new MethodNotAllowedHttpException('You can\'t edit a page.');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int                      $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        throw new MethodNotAllowedHttpException('You can\'t edit a page.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $file_path = sprintf('%s/%s.md', Auth::user()->getAuthIdentifier(), $id);
        if (!Storage::disk('pages')->exists($file_path)) {
            throw new FileNotFoundException('Cette page n\'existe pas.');
        }

        $json = [
            'success' => Storage::disk('pages')->delete($file_path),
        ];

        return response()->json($json);
    }
}