<?php

namespace CCDN\Helpers\DB;

use CCDN\Helpers\Entities\Post;
use CCDN\Helpers\Settings;

class PostMapper extends Model
{
    /**
     * @var int
     */
    public $partLength;


    public function __construct()
    {
        parent::__construct();
        $this->partLength = Settings::DEFAULT_CHUNK_LENGTH;
    }

    /**
     * @param  int  $chunk
     *
     * @return Post[]
     */
    public function selectPosts($chunk)
    {
        $posts = [];
        $offset = $chunk * $this->partLength;
        $fields = ' `id`, `alt_name`, `metatitle`, `xfields`, `date`, `title`, `category`, `full_story`, `short_story`';
        $postStatusField = Settings::get('post_status_field');
        $queryResult = $this->select("SELECT {$fields} FROM  `{$this->getPrefix()}_post` ORDER BY `id` DESC LIMIT {$this->partLength} OFFSET {$offset}",
            true);

        foreach ($queryResult as $rawPost) {
            $post = new Post($rawPost);
            if ($post->getField($postStatusField) === '0') {
                continue;
            }
            $posts[$rawPost['id']] = $post;
        }

        return $posts;
    }
}
