<?php

namespace KupShop\ElninoBundle\Util\ContentAPI;

use KupShop\I18nBundle\Util\PriceConverter;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Context\VatContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Price\Price;

class GoogleApi
{
    protected $currencies = [];

    protected $service = [];
    protected $batchId = 0;

    protected $entries = [];
    /**
     * @var CurrencyContext
     */
    private $currencyContext;

    /**
     * @var VatContext
     */
    private $vatContext;

    public function __construct(CurrencyContext $currencyContext)
    {
        $this->currencyContext = $currencyContext;
    }

    public function addEntry($row)
    {
        foreach ($this->currencies as $currency => $merch) {
            $product = new \Google_Service_ShoppingContent_Product();
            $product->setId($row['id']);
            $product->setOfferId($row['id']);
            $product->setTargetCountry($merch['country']);
            $product->setContentLanguage($merch['lang']);
            $product->setChannel('online');

            $price = new \Google_Service_ShoppingContent_Price();

            $productPrice = toDecimal($row['price'])->addDiscount($row['discount']);

            $currencyObject = $this->currencyContext->getAll()[$currency];
            $priceconvertor = new PriceConverter();
            $convertedPrice = $priceconvertor->convert($this->currencyContext->getActiveId(), $currencyObject->getId(), $productPrice);

            $vat = $this->vatContext->getVat($row['vat_id']);
            if (($vat['vat_eur'] ?? false) && $currency == 'EUR') {
                $row['vat'] = $vat['vat_eur'];
            }

            $p = new Price($convertedPrice, $currencyObject, $row['vat']);
            $price->setValue($p->getPriceWithVat()->asFloat());
            $price->setCurrency($currency);
            $product->setPrice($price);
            $product->setAvailability($this->getAvailability($row));

            $entry = new \Google_Service_ShoppingContent_ProductsCustomBatchRequestEntry();
            $entry->setMethod('insert');
            $entry->setProduct($product);
            $entry->setBatchId(++$this->batchId);
            $entry->setFeedId($merch['feed_id']);
            $entry->setMerchantId($merch['merchant_id']);

            $this->entries[$currency][] = $entry;
        }
    }

    public function getAvailability($row)
    {
        if (!empty($row['elnino_store']) && in_array((int) $row['elnino_store'], [50, 51])) {
            return $row['in_store_suppliers'] > 0 ? 'in stock' : 'out of stock';
        }

        return $row['in_store'] > 0 ? 'in stock' : 'out of stock';
    }

    public function sendBatch()
    {
        foreach ($this->currencies as $currency => $merch) {
            try {
                if (empty($this->entries[$currency])) {
                    continue;
                }

                $batchRequest = new \Google_Service_ShoppingContent_ProductsCustomBatchRequest();
                $batchRequest->setEntries($this->entries[$currency]);

                $result = $merch['service']->products->custombatch($batchRequest);

                $this->entries[$currency] = [];
            } catch (\Exception $e) {
                if (!isDevelopment()) {
                    $raven = getRaven();
                    $raven->captureException($e);
                } else {
                    throw $e;
                }
            }
        }
    }

    protected function getCountryFromCurrency($currency)
    {
        switch ($currency) {
            case 'EUR': return 'SK';
            default: return 'CZ';
        }
    }

    protected function getLanguageFromCurrency($currency)
    {
        switch ($currency) {
            case 'EUR': return 'sk';
            default: return 'cs';
        }
    }

    public function isEnabled()
    {
        if (isBeta()) {
            return false;
        }

        $enabled = false;
        $settings = \Settings::getDefault();

        foreach ($this->currencyContext->getAll() as $currency) {
            if (!empty($settings->custom[$currency->getId().'_merchant_id']) && !empty($settings->custom[$currency->getId().'_merchant_feed_id'])) {
                $this->currencies[$currency->getId()] = [
                    'currency' => $currency->getId(),
                    'merchant_id' => $settings->custom[$currency->getId().'_merchant_id'],
                    'feed_id' => $settings->custom[$currency->getId().'_merchant_feed_id'],
                    'country' => $settings->custom[$currency->getId().'_merchant_country'] ?? $this->getCountryFromCurrency($currency->getId()),
                    'lang' => $settings->custom[$currency->getId().'_merchant_lang'] ?? $this->getLanguageFromCurrency($currency->getId()),
                    'service' => $this->getService(strtolower($currency->getId())),
                ];
                $enabled = true;
            }
        }

        return $enabled;
    }

    protected function getService($currency)
    {
        if (ServiceContainer::getContainer()->hasParameter("shop.content_api.{$currency}.json")) {
            $api_json = ServiceContainer::getContainer()->getParameter("shop.content_api.{$currency}.json");
        } else {
            $api_json = 'merchant-center-1576054124748-9fc6a14b1668.json';
        }

        $key_file_location = realpath(__DIR__."/{$api_json}");

        if (!file_exists($key_file_location)) {
            return false;
        }

        $client = new \Google_Client();
        $client->setApplicationName('KupShop');
        $client->setAuthConfig($key_file_location);
        $client->setScopes(['https://www.googleapis.com/auth/content']);

        return $this->service = new \Google_Service_ShoppingContent($client);
    }

    /**
     * @required
     */
    public function setVatContext(VatContext $vatContext): void
    {
        $this->vatContext = $vatContext;
    }
}
