<?php

namespace LivraisonParSecteurs;

use LivraisonParSecteurs\Model\LpsSecteurQuery;
use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Core\Translation\Translator;
use Thelia\Install\Database;
use Thelia\Model\AddressQuery;
use Thelia\Model\Country;
use Thelia\Model\OrderPostage;
use Thelia\Module\AbstractDeliveryModule;
use Thelia\Module\Exception\DeliveryException;

class LivraisonParSecteurs extends AbstractDeliveryModule
{
    /** @var string */
    const DOMAIN_NAME = 'livraisonparsecteurs';
    const MESSAGE_DOMAIN = "livraisonparsecteurs";


    /**
     * @param ConnectionInterface|null $con
     */
    public function postActivation(ConnectionInterface $con = null)
    {
        $database = new Database($con->getWrappedConnection());
        $database->insertSql(null, array(__DIR__ . '/Config/thelia.sql'));
        $database->insertSql(null, array(__DIR__ . '/Config/insert.sql'));
    }

    /**
     * This method is called by the Delivery  loop, to check if the current module has to be displayed to the customer.
     * Override it to implements your delivery rules/
     *
     * If you return true, the delivery method will de displayed to the customer
     * If you return false, the delivery method will not be displayed
     *
     * @param Country $country the country to deliver to.
     *
     * @return boolean
     */
    public function isValidDelivery(Country $country)
    {
        // Get current addressId
        $currentAddressId = $this->getRequest()->request->get('address_id');

        if (empty($currentAddressId)) {
            if (null !== $customer = $this->getRequest()->getSession()->getCustomerUser()) {
                $currentAddressId = AddressQuery::create()
                    ->filterByCustomer($customer)
                    ->filterByIsDefault(1)
                    ->select('ID')
                    ->findOne();
            } else {
                return false;
            }
        }
    }


    /**
     * Calculate and return delivery price in the shop's default currency
     *
     * @param Country $country the country to deliver to.
     *
     * @return OrderPostage|float             the delivery price
     * @throws DeliveryException if the postage price cannot be calculated.
     */
    public function getPostage(Country $country)
    {
        if (! $this->isValidDelivery($country)) {
            throw new DeliveryException(
                Translator::getInstance()->trans("This module cannot be used on the current cart.")
            );
        }

        return LpsSecteurQuery::create()->findOneByActive(1)->getPrice();
    }

}
