<?php

namespace Shop\Commands;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use samdark\sitemap\Sitemap as SitemapLib;
use Diamond\Repositories\Page as pageRepo;
use Shop\Repositories\Product as productRepo;
use Shop\Repositories\Category as categoryRepo;

/**
 * Description of SitemapCommand
 *
 * @author Admin
 */
class Sitemap extends Command
{

    protected $pageRepo;
    protected $productRepo;
    protected $categoryRepo;
    protected $mainConf;

    function __construct($name = null,
                         \Diamond\Config\Main $mainConf,
                         pageRepo $pageRepo,
                         productRepo $productRepo,
                         categoryRepo $categoryRepo
    )
    {

        $this->pageRepo = $pageRepo;
        $this->productRepo = $productRepo;
        $this->categoryRepo = $categoryRepo;
        $this->mainConf = $mainConf;

        parent::__construct($name);
    }

    protected function configure()
    {
        $this->setName('tools:sitemap')
            ->setDescription('Create simemap.xml');
    }

    /**
     *
     * @param type $sitemap
     * @param type $baseurl
     */
    protected function createPages(SitemapLib $sitemap)
    {

        $pages = $this->pageRepo->buildQuery()
            ->filterByActive("Y")
            ->filterBySystem("N")
            ->filterByDomainId(1)
            ->find();

        foreach ($pages as $page) {

            $sitemap->addItem(
                $this->createUrl($page->getUrl())
                , time(), SitemapLib::DAILY, 1);
        }

    }

    /**
     *
     * @param type $_url
     * @return type
     */
    protected function createUrl($_url)
    {
        $conf = $this->mainConf;
        $urlSuffix = $_url . $conf->getUrl_suffix();
        if ($urlSuffix == '/' . $conf->getUrl_suffix()) {
            $urlSuffix = '/';
        }
        return trim(getenv("BASE_URL"),"/"). $urlSuffix;
    }

    /**
     *
     * @param SitemapLib $sitemap
     * @param type $baseurl
     */
    protected function createCatalogPages(SitemapLib $sitemap)
    {
        $categories = $this->categoryRepo->findAll();

        foreach ($categories as $category) {

            $sitemap->addItem(
                $this->createUrl(sprintf(
                    "/catalog/%s", $category->getAlias()
                ))
                , time(), SitemapLib::DAILY, 0.9);
        }
    }

    /**
     *
     * @param SitemapLib $sitemap
     * @param type $baseurl
     */
    protected function createProductPages(SitemapLib $sitemap)
    {

        $products = $this
            ->productRepo
            ->buildQuery()
            ->filterByActive("Y")
            ->find();

        foreach ($products as $product) {
            $sitemap->addItem(
                $this->createUrl(
                    sprintf(
                        "/catalog/%s/%s-%s", $product->getCategory()->getAlias(), $product->getId(),
                        \Shop\Helpers\Text::str2url($product->getTitle())
                    ))
                , time(), SitemapLib::DAILY, 0.8);
        }
    }

    /**
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {

        $sitemap = new SitemapLib(BASEPATH . '/public_html/sitemap.xml');


        //Генерируем страницы
        $this->createPages($sitemap);

        //Генерируем страницы разделов каталога
        $this->createCatalogPages($sitemap);
        //генерируем страницы товаров
        $this->createProductPages($sitemap);


        try {
            $sitemap->write();
            $output->writeln("sitemap.xml create completed!");
        } catch (\Exception $ex) {
            $output->writeln("sitemap.xml create error!");
        }
    }

}