<?php

namespace LivraisonParSecteurs\Loop;

use LivraisonParSecteurs\Model\LpsAreaCityQuery;
use Propel\Runtime\ActiveQuery\Criteria;
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 Thelia\Type\EnumListType;
use Thelia\Type\TypeCollection;

/**
 * Class AreaCitiesLoop
 * @package LivraisonParSecteurs\Loop
 */
class AreaCitiesLoop 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_cities) {

            $loopResultRow = new LoopResultRow($lps_area_cities);
            $loopResultRow
                ->set("ID", $lps_area_cities->getId())
                ->set("ZIPCODE", $lps_area_cities->getZipcode())
                ->set("TITLE", $lps_area_cities->getTitle())
                ->set("LATITUDE", $lps_area_cities->getLatitude())
                ->set("LONGITUDE", $lps_area_cities->getLongitude())
            ;
            $loopResult->addRow($loopResultRow);
        }
        return $loopResult;
    }

    /**
     * @inheritdoc
     */
    protected function getArgDefinitions()
    {
        return new ArgumentCollection(
            Argument::createIntListTypeArgument('area_id'),
            Argument::createEnumListTypeArgument('order',
                ['title', 'zipcode'], 'title')
        );
    }

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

        if (null != $id = $this->getAreaId()) {
            $area->filterByIdArea($id);
        }

        foreach ($this->getOrder() as $order) {
            switch ($order) {
                case 'title':
                    $area->orderByTitle();
                    break;
                case 'zipcode':
                    $area->orderByZipcode()->orderByTitle();
                    break;
            }
        }

        return $area;
    }

}
