<?php

namespace Acms\Services\StaticExport\Generator;

use Acms\Services\StaticExport\Contracts\Generator;
use Acms\Services\Facades\Storage;
use SQL;
use DB;
use ACMS_Filter;

class EntryGenerator extends Generator
{
    /**
     * @var int
     */
    protected $numberOfEntries;

    protected function getName()
    {
        return 'エントリーの書き出し';
    }

    protected function getTasks()
    {
        return $this->numberOfEntries;
    }

    /**
     * @return void
     */
    protected function main()
    {
        $entries = $this->getEntries();
        $this->numberOfEntries = count($entries);
        $this->logger->start($this->getName(), $this->getTasks());

        foreach ($entries as $entry) {
            $eid = $entry['entry_id'];
            $info = array(
                'bid' => BID,
                'eid' => $eid,
            );
            try {
                $url = acmsLink($info);
                $this->request($url, $info);
            } catch ( \Exception $e ) {
                $this->logger->error($e->getMessage(), $url);
            }
        }
    }

    /**
     * @param string $data
     * @param string $code
     * @param object $info
     * @return void
     */
    protected function callback($data, $code, $info)
    {
        if ( $this->logger ) {
            $this->logger->processing();
        }
        if ( empty($data) || $code != '200' ) {
            $this->logger->error('データの取得に失敗しました。', acmsLink($info), $code);
            return;
        }
        $destination = $this->destination->getDestinationPath() . $this->destination->getBlogCode();
        $blog_url = acmsLink(array('bid' => BID));
        $url = acmsLink($info);
        $file = substr($url, strlen($blog_url));
        $file = $destination . $file;
        if ( is_dir($file) ) {
            $file = $file . 'index.html';
        }

        try {
            Storage::makeDirectory(dirname($file));
            Storage::put($file, $data);
        } catch ( \Exception $e ) {
            $this->logger->error('データの書き込みに失敗しました。', $file);
        }
    }

    /**
     * @return array
     */
    private function getEntries()
    {
        $SQL = SQL::newSelect('entry');
        $SQL->addSelect('entry_id');
        $SQL->addLeftJoin('blog', 'blog_id', 'entry_blog_id');
        $SQL->addWhereOpr('entry_blog_id', BID);
        $SQL->addWhereOpr('entry_status', 'open');

        return DB::query($SQL->get(dsn()), 'all');
    }
}