<?php

namespace pictpostpersonal\service;

use pictpostpersonal\Environment;
use pictpostpersonal\Utility;


class PluginApiService
{
    private $db;
    private $setting;
    private $nsfw_ans;

    function __construct($db, $setting, $nsfw_ans)
    {
        $this->db = $db;
        $this->setting = $setting;
        $this->nsfw_ans = $nsfw_ans;
    }

    public function getArticles(string $tags, string $order, $limit = 0, $offset = 0): array
    {
        $article_moldel = new \pictpostpersonal\model\Article($this->db, $this->setting);
        $order = strtolower($order);
        switch ($order) {
            case 'created_at':
                $order = ['created_at desc'];
                break;
            case 'updated_at':
                $order = ['updated_at desc'];
                break;
            case 'views':
                $order = ['views desc'];
                break;
            case 'likes':
                $order = ['like desc'];
                break;
            default:
                $order = ['created_at desc'];
                break;
        }
        ['articles' => $articles, 'count' => $total_count] = $article_moldel->searchByTagWithCount($tags, false, $order, $limit, $offset);
        foreach ($articles as $key => $item) {
            $articles[$key]['url'] = SITE_URL . Environment::getLogUrl($item);
            $articles[$key]['caption'] = Utility::createCaption($item['contents']);;
            $articles[$key]['created_at'] = s($item['created_at']);
            $articles[$key]['updated_at'] = s($item['updated_at']);
            $title = s($item['title']);
            $articles[$key]['title'] = $title;
            $articles[$key]['nsfw_type'] = $item['nsfw'] ? '0' : '1';
            $articles[$key]['nsfw_status'] = $this->nsfw_ans ? '0' : '1';

            $thumbnail_class = '';
            if ($item['nsfw']) {
                $thumbnail_class .= ' thumb_nsfw';
            }
            if ($this->nsfw_ans) {
                $thumbnail_class .= ' thumb_nsfw_consent';
            }
            if ($item['media_count'] == 0) {
                $thumbnail_class .= ' thumb_text';
                $articles[$key]['thumbnail_title'] = $title;
            } else {
                $articles[$key]['thumbnail_title'] = '';
            }
            $articles[$key]['thumbnail_class'] = $thumbnail_class;

            $thumbnail = Utility::getThumbnailUrl($item, $this->nsfw_ans);
            $articles[$key]['thumbnail_path'] =  $thumbnail; //NSFW同意を考慮したサムネイル

            if ($item['media_count'] == 0) {
                $thumbnail = Utility::getThumbnailUrl($item, $this->nsfw_ans);
                $articles[$key]['raw_thumbnail_path'] = $thumbnail;
            } else {
                $thumbnail = Utility::getThumbnailUrl($item, true);
                $articles[$key]['raw_thumbnail_path'] = $thumbnail;
            }
        }
        return [$articles, $total_count];
    }
}
