<?php

namespace PointRetrait\Loop;

use PointRetrait\Model\PdrPlacesQuery;
use PointRetrait\Model\PdrScheduleQuery;
use PointRetrait\PointRetrait;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;

/**
 * Class GeneralLoop
 * @package LivraisonParSecteurs\Loop
 */
class GeneralLoop extends BaseLoop implements PropelSearchLoopInterface
{
    public $countable = false;
    public $timestampable = false;
    public $versionable = false;


    /**
     * @param LoopResult $loopResult
     *
     * @return LoopResult
     */
    public function parseResults(LoopResult $loopResult)
    {
        foreach ($loopResult->getResultDataCollection() as $places) {

            $loopResultRow = new LoopResultRow($places);

            $schedule = PdrScheduleQuery::create()->findById($places->getId());
            $deliveryDays = "";
            foreach ($schedule as $day) {
                $deliveryDays .= PointRetrait::getDayLabel($day->getDay()) . ', ';
            }
            $deliveryDays = substr($deliveryDays, 0, strlen($deliveryDays)-2);


            $loopResultRow
                ->set("ID", $places->getId())
                ->set("TITLE", $places->getTitle())
                ->set("ACTIVE", $places->getActive())
                ->set("PRICE", $places->getPrice())
                ->set("MINIMUM_AMOUNT", $places->getMinimumAmount())
                ->set("DELIVERY_DAYS", $deliveryDays)
                ->set("LATITUDE", $places->getLatitude())
                ->set("LONGITUDE", $places->getLongitude())
                ->set("ADDRESS1", $places->getAddress1())
                ->set("ADDRESS2", $places->getAddress2())
                ->set("ZIPCODE", $places->getZipcode())
                ->set("CITY", $places->getCity())
                ->set("ACCESS_COMMENT", $places->getAccessComment())
            ;
            $loopResult->addRow($loopResultRow);
        }
        return $loopResult;
    }

    /**
     * @inheritdoc
     */
    protected function getArgDefinitions()
    {
        return new ArgumentCollection(
            Argument::createIntListTypeArgument('id'),
            Argument::createIntListTypeArgument('active')
        );
    }

    /**
     * @inheritdoc
     */
    public function buildModelCriteria()
    {
        $places = PdrPlacesQuery::create();

        /* Filtrage éventuel */
        if (null != $id = $this->getId()) {
            $places->filterById($id);
        }
        if (null != $active = $this->getActive()) {
            $places->filterByActive($active);
        }

        return $places->orderByTitle();
    }

}
