<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace ArtabanMarketplace\Loop;

use Thelia\Core\Template\Loop\Delivery;
use Thelia\Core\Event\Delivery\DeliveryPostageEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Model\AreaDeliveryModuleQuery;
use Thelia\Model\Cart as CartModel;
use Thelia\Model\CountryQuery;
use Thelia\Model\Module;
use Thelia\Module\DeliveryModuleInterface;
use Thelia\Module\Exception\DeliveryException;
use ArtabanMarketplaceColissimo\ArtabanMarketplaceColissimo;
Use Thelia\Model\CartItemQuery;
use ArtabanMarketplace\Model\AmpSellerProductQuery;

/**
 * Description of deliveryLoop
 *
 * @author LENGY
 */
class deliveryLoop extends Delivery {

    public function parseResults(LoopResult $loopResult) {
        $cart = $this->getCurrentRequest()->getSession()->getSessionCart($this->dispatcher);
        $address = $this->getDeliveryAddress();

        $country = $this->getCurrentCountry();
        if (null === $country) {
            if ($address !== null) {
                $country = $address->getCountry();
            } else {
                $country = CountryQuery::create()->findOneByByDefault(true);
            }
        }

        $state = $this->getCurrentState();
        if (null === $state) {
            if ($address !== null) {
                $state = $address->getState();
            }
        }

        $virtual = $cart->isVirtual();

        /** @var Module $deliveryModule */
        foreach ($loopResult->getResultDataCollection() as $deliveryModule) {
            $areaDeliveryModule = AreaDeliveryModuleQuery::create()
                    ->findByCountryAndModule($country, $deliveryModule, $state)
            ;

            if (null === $areaDeliveryModule && false === $virtual) {
                continue;
            }

            /** @var DeliveryModuleInterface $moduleInstance */
            $moduleInstance = $deliveryModule->getDeliveryModuleInstance($this->container);

            if (true === $virtual && false === $moduleInstance->handleVirtualProductDelivery() && false === $this->getBackendContext()
            ) {
                continue;
            }

            $loopResultRow = new LoopResultRow($deliveryModule);

            try {
                // Check if module is valid, by calling isValidDelivery(),
                // or catching a DeliveryException.
                /** @var CartModel $cart */
                $cart->getAddressDeliveryId();
                $deliveryPostageEvent = new DeliveryPostageEvent($moduleInstance, $cart, $address, $country, $state);
                $this->dispatcher->dispatch(
                        TheliaEvents::MODULE_DELIVERY_GET_POSTAGE, $deliveryPostageEvent
                );

                if ($deliveryPostageEvent->isValidModule()) {


                    //$postage = $deliveryPostageEvent->getPostage();

                    $artabanMarketplaceColissimo = new ArtabanMarketplaceColissimo();

                    $areaId = $artabanMarketplaceColissimo->getAreaForCountry($country)->getId();

                    $sellers_id_array = $this::generateArraySellerId($event);
                    $totalPostage = 0;
                    foreach ($sellers_id_array as $sellerId) {
                        $sellerPostage = $artabanMarketplaceColissimo->getPostageAmountSeller($sellerId, $areaId);
                        $totalPostage = $totalPostage + $sellerPostage;
                    }



                    $loopResultRow
                            ->set('ID', $deliveryModule->getId())
                            ->set('CODE', $deliveryModule->getCode())
                            ->set('TITLE', $deliveryModule->getVirtualColumn('i18n_TITLE'))
                            ->set('CHAPO', $deliveryModule->getVirtualColumn('i18n_CHAPO'))
                            ->set('DESCRIPTION', $deliveryModule->getVirtualColumn('i18n_DESCRIPTION'))
                            ->set('POSTSCRIPTUM', $deliveryModule->getVirtualColumn('i18n_POSTSCRIPTUM'))
                            ->set('POSTAGE', $totalPostage)
                            ->set('POSTAGE_TAX', 0000)
                            ->set('POSTAGE_UNTAXED', 0000)
                            ->set('POSTAGE_TAX_RULE_TITLE', 'Défaut Marketplace Artaban')
                            ->set('DELIVERY_DATE', $deliveryPostageEvent->getDeliveryDate())
                    ;

                    // add additional data if it exists
                    if ($deliveryPostageEvent->hasAdditionalData()) {
                        foreach ($deliveryPostageEvent->getAdditionalData() as $key => $value) {
                            $loopResultRow->set($key, $value);
                        }
                    }

                    $this->addOutputFields($loopResultRow, $deliveryModule);

                    $loopResult->addRow($loopResultRow);
                }
            } catch (DeliveryException $ex) {
                // Module is not available
            }
        }

        return $loopResult;
    }

    /**
     * @return Array of unique id seller extracted form the items cart
     */
    protected function generateArraySellerId() {

        $cart_id = $cart = $this->getCurrentRequest()->getSession()->getSessionCart($this->dispatcher)->getId();
        $cart_items = CartItemQuery::create()->filterByCartId($cart_id)->find();
        $sellers_id_all_array = array();
        foreach ($cart_items as $item) {
            $seller_product = AmpSellerProductQuery::create()->findOneByProductId($item->getProductId());
            $sellers_id_all_array[] = $seller_product->getAmpSellerId();
        }
        return array_unique($sellers_id_all_array);
    }

}
