<?php

namespace LivraisonParSecteurs\Loop;

use LivraisonParSecteurs\LivraisonParSecteurs;
use LivraisonParSecteurs\Model\LpsAreaCityQuery;
use LivraisonParSecteurs\Model\LpsAreaScheduleQuery;
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;
use LivraisonParSecteurs\Model\LpsAreaQuery;

/**
 * Class AreaLoop
 * @package LivraisonParSecteurs\Loop
 */
class AreaLoop 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 $lps_area) {

            $loopResultRow = new LoopResultRow($lps_area);

            $schedule = LpsAreaScheduleQuery::create()->findByIdArea($lps_area->getId());
            $deliveryDays = "";
            foreach ($schedule as $day) {
                $deliveryDays .= LivraisonParSecteurs::getDayLabel($day->getDay()) . ', ';
            }
            $deliveryDays = substr($deliveryDays, 0, strlen($deliveryDays)-2);

            $citiesCount = LpsAreaCityQuery::create()->findByIdArea($lps_area->getId())->count();

            $loopResultRow
                ->set("ID", $lps_area->getId())
                ->set("TITLE", $lps_area->getTitle())
                ->set("ACTIVE", $lps_area->getActive())
                ->set("PRICE", $lps_area->getPrice())
                ->set("MINIMUM_AMOUNT", $lps_area->getMinimumAmount())
                ->set("DELIVERY_DAYS", $deliveryDays)
                ->set("COVERED_CITIES_NUMBER", $citiesCount)
            ;
            $loopResult->addRow($loopResultRow);
        }
        return $loopResult;
    }

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

    /**
     * @inheritdoc
     */
    public function buildModelCriteria()
    {
        $area = LpsAreaQuery::create();

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

        return $area->orderByTitle();
    }

}
