<?php

/* * ********************************************************************************** */
/*      This file is part of the Thelia package.                                     */
/*                                                                                   */
/*      Copyright (c) OpenStudio                                                     */
/*      email : dev@thelia.net                                                       */
/*      web : http://www.thelia.net                                                  */
/*                                                                                   */
/*      For the full copyright and license information, please view the LICENSE.txt  */
/*      file that was distributed with this source code.                             */
/* * ********************************************************************************** */
/* * ********************************************************************************** */

namespace ArtabanMarketplace\Loop;

use ArtabanMarketplace\Model\AmpSeller;
use ArtabanMarketplace\Model\AmpSellerQuery;
use ArtabanMarketplace\Model\Map\AmpSellerTableMap;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseI18nLoop;
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 SellerLoop
 * @package ArtabanMarketplace\Loop
 */
class SellerLoop extends BaseI18nLoop implements PropelSearchLoopInterface {

    /**
     * @param LoopResult $loopResult
     *
     * @return LoopResult
     */
    public function parseResults(LoopResult $loopResult) {
        /** @var AmpSeller $seller */
        foreach ($loopResult->getResultDataCollection() as $seller) {
            $loopResultRow = new LoopResultRow($seller);

            $loopResultRow
                    ->set('ID', $seller->getId())
                    ->set('REF', $seller->getRef())
                    ->set("ADDRESS1", $seller->getAddress1())
                    ->set("ADDRESS2", $seller->getAddress2())
                    ->set("ADDRESS3", $seller->getAddress3())
                    ->set("ZIPCODE", $seller->getZipcode())
                    ->set("CITY", $seller->getCity())
                    ->set("COUNTRY_ID", $seller->getCountryId())
                    ->set("EMAIL", $seller->getEmail())
                    ->set("PHONE", $seller->getPhone())
                    ->set("FAX", $seller->getFax())
                    ->set("URL", $seller->getUrl())
                    ->set("FACEBOOK", $seller->getFacebook())
                    ->set("TWITTER", $seller->getTwitter())
                    ->set("PINTEREST", $seller->getPinterest())
                    ->set("GOOGLE", $seller->getGoogle())
                    ->set("YOUTUBE", $seller->getYoutube())
                    ->set("INSTAGRAM", $seller->getInstagram())
                    ->set("LAT", $seller->getLatitude())
                    ->set("LON", $seller->getLongitude())
                    ->set("CREATE_DATE", $seller->getCreatedAt())
                    ->set("UPDATE_DATE", $seller->getUpdatedAt())
                    ->set("VISIBLE", $seller->getVisible())
            ;

            if ($seller->hasVirtualColumn('i18n_TITLE')) {
                $loopResultRow->set("TITLE", $seller->getVirtualColumn('i18n_TITLE'));
            }

            if ($seller->hasVirtualColumn('i18n_ACCESS')) {
                $loopResultRow->set("ACCESS", $seller->getVirtualColumn('i18n_ACCESS'));
            }

            if ($seller->hasVirtualColumn('i18n_DESCRIPTION')) {
                $loopResultRow->set("DESCRIPTION", $seller->getVirtualColumn('i18n_DESCRIPTION'));
            }

            if ($this->getWithPrevNextInfo()) {
                $previous = $this->getPrevious($seller);
                $next = $this->getNext($seller);
                $loopResultRow
                        ->set("HAS_PREVIOUS", $previous != null ? 1 : 0)
                        ->set("HAS_NEXT", $next != null ? 1 : 0)
                        ->set("PREVIOUS", $previous != null ? $previous->getId() : -1)
                        ->set("NEXT", $next != null ? $next->getId() : -1);
            }

            $loopResult->addRow($loopResultRow);
        }

        return $loopResult;
    }

    /**
     * @inheritdoc
     */
    protected function getArgDefinitions() {
        return new ArgumentCollection(
                Argument::createIntListTypeArgument('id'), Argument::createIntListTypeArgument('admin_id'), Argument::createIntListTypeArgument('country_id'), Argument::createIntListTypeArgument('content_id'), Argument::createIntListTypeArgument('folder_id'), Argument::createIntListTypeArgument('brand_id'), Argument::createIntListTypeArgument('product_id'), Argument::createBooleanTypeArgument('visible'), Argument::createAnyListTypeArgument('city'), Argument::createBooleanTypeArgument('with_prev_next_info', false), Argument::createEnumListTypeArgument('order', [
                    'id',
                    'id-reverse',
                    'date',
                    'date-reverse',
                    'title',
                    'title-reverse',
                    'address1',
                    'address1-reverse',
                    'zipcode',
                    'zipcode-reverse',
                    'city',
                    'city-reverse'
                        ], 'id')
        );
    }

    /**
     * @inheritdoc
     */
    public function buildModelCriteria() {
        $query = AmpSellerQuery::create();

        // manage translations
        $this->configureI18nProcessing(
                $query, [
            'TITLE',
            'DESCRIPTION',
            'ACCESS'
                ], null, 'ID', $this->getForceReturn()
        );

        if (null != $id = $this->getId()) {
            $query->filterById($id);
        }
        
        if (null != $country_id = $this->getCountryId()) {
            $query->filterByCountryId($country_id);
        }

        if (null != $city = $this->getCity()) {
            $query->filterByCity($city);
        }

        if (null != $visible = $this->getVisible()) {
            $query->filterByVisible($visible);
        }



        if ($this->getBackendContext() === true) {
            $query = $this->getAdminArtabanMarketplace($query);
        }

        foreach ($this->getOrder() as $order) {
            switch ($order) {
                case 'id' :
                    $query->orderById();
                    break;
                case 'id-reverse' :
                    $query->orderById(Criteria::DESC);
                    break;
                case 'date' :
                    $query->orderByCreatedAt();
                    break;
                case 'date-reverse' :
                    $query->orderByCreatedAt(Criteria::DESC);
                    break;
                case 'title' :
                    $query->useAmpSellerI18nQuery()->orderByTitle()->endUse();
                    break;
                case 'title-reverse' :
                    $query->useAmpSellerI18nQuery()->orderByTitle(Criteria::DESC)->endUse();
                    break;
                case 'address1' :
                    $query->orderByAddress1();
                    break;
                case 'address1-reverse' :
                    $query->orderByAddress1(Criteria::DESC);
                    break;
                case 'zipcode' :
                    $query->orderByZipcode();
                    break;
                case 'zipcode-reverse' :
                    $query->orderByZipcode(Criteria::DESC);
                    break;
                case 'city' :
                    $query->orderByCity();
                    break;
                case 'city-reverse' :
                    $query->orderByCity(Criteria::DESC);
                    break;
                default:
                    break;
            }
        }

        return $query;
    }

    /**
     * @param AmpSeller $seller
     * @return AmpSeller
     */
    protected function getPrevious($seller) {
        $query = AmpSellerQuery::create();

        foreach ($this->getOrder() as $order) {
            switch ($order) {
                case 'id' :
                    $query->orderById(Criteria::DESC);
                    $query->filterById($seller->getId(), Criteria::LESS_THAN);
                    break;
                case 'id-reverse' :
                    $query->orderById();
                    $query->filterById($seller->getId(), Criteria::GREATER_THAN);
                    break;
                default:
                    $query->orderById(Criteria::DESC);
                    $query->filterById($seller->getId(), Criteria::LESS_THAN);
                    break;
            }
        }

        return $query->findOne();
    }

    /**
     * @param AmpSeller $seller
     * @return AmpSeller
     */
    protected function getNext($seller) {
        $query = AmpSellerQuery::create();

        foreach ($this->getOrder() as $order) {
            switch ($order) {
                case 'id' :
                    $query->orderById();
                    $query->filterById($seller->getId(), Criteria::GREATER_THAN);
                    break;
                case 'id-reverse' :
                    $query->orderById(Criteria::DESC);
                    $query->filterById($seller->getId(), Criteria::LESS_THAN);
                    break;
                default:
                    $query->orderById();
                    $query->filterById($seller->getId(), Criteria::GREATER_THAN);
                    break;
            }
        }

        return $query->findOne();
    }

    /** NOT USED
     * @param AmpSellerQuery $query
     * @return AmpSellerQuery
     */
    protected function getAdminArtabanMarketplace($query) {
        /** @var \Thelia\Model\Admin $admin */
        $admin = $this->securityContext->getAdminUser();

        if ($admin === null) {
            return $query;
        }

        if ($admin->getProfileId() === null) {
            return $query;
        }

        // If the current admin has an allowed profile_id, let him see all the sellers
        if (null != $configProfileIds = \ArtabanMarketplace\AmpSeller::getConfigValue(\ArtabanMarketplace\AmpSeller::CONFIG_ALLOW_PROFILE_ID)) {
            $profileIds = explode(',', $configProfileIds);

            if (in_array($admin->getProfileId(), $profileIds)) {
                return $query;
            }
        }

        return $query->useAmpSellerAdminQuery()->filterByAdminId($admin->getId())->endUse();
    }

}
