<?php

namespace Webkul\WooCommerceBundle\Connector\Writer;


use Symfony\Component\HttpFoundation\Response;
use Webkul\WooCommerceBundle\Connector\Writer\BaseWriter;
use Webkul\WooCommerceBundle\Entity\DataMapping;
use Webkul\WooCommerceBundle\Traits\DataMappingTrait;
use Webkul\WooCommerceBundle\Listener\ClassDefinationForCompatibility;

$obj = new ClassDefinationForCompatibility();
$obj->objectCreate();

/**
 * Add attribute options to WooCommerce Api
 *
 * @author    Webkul Software Pvt Ltd
 * @copyright 2010-2020 Webkul pvt. ltd.
 * @license   https://store.webkul.com/license.html
 */
class AttributeOptionWriter extends BaseWriter implements \ItemWriterInterface
{
    use DataMappingTrait;

    const AKENEO_ENTITY_NAME = 'option';
    const AKENEO_ATTRIBUTE_ENTITY_NAME = 'attribute';
    const ACTION_ADD = 'addOption';
    const ACTION_UPDATE = 'updateOption';
    const SETTING_SECTION = 'woocommerce_connector_settings';
    const CODE_ALREADY_EXIST = 'term_exists';
    const CODE_DUPLICATE_EXIST = 'duplicate_term_slug';
    const CODE_NOT_EXIST = 'woocommerce_rest_term_invalid';
    const RELATED_INDEX = null;
    const ACTION_GET = '';
    const WPML_CODE_ALREADY_EXIST = 'A term with the name provided already exists in this taxonomy.';
    const WPML_GET_DATA = 'getAttributeOption';
    const WPML_INVALID_CODE = 'Data Error';
    
    protected $requiredApiParams;
    protected $obj = '';
    protected $parameters;

    /**
     * write products to WooCommerce Api
     */
    public function write(array $items)
    {
        if (!$this->parameters) {
            $this->parameters = $this->stepExecution->getJobParameters();
        }
        $exportProfile = $this->parameters->has('exportProfile') && (!empty($this->parameters->get('exportProfile'))) ? $this->parameters->get('exportProfile') : "";
        $settings = $this->connectorService->getMultiSetting('settings');
        $classex = 'Webkul\WpmlProductBundle\Connector\Writer\AttributeOption';
        if (class_exists($classex) && isset($settings['enable_wpml']) && $settings['enable_wpml'] == "on"){
            if($this->obj == ''){
                $this->obj = new $classex($this->connectorService);
                $this->obj->setStepExecution($this->stepExecution);
                $this->obj->writeWpml($items,$exportProfile);
            } else {
                $this->obj->writeWpml($items,$exportProfile);
            }
        } else {
            $this->writeSimple($items,$exportProfile);
        }
    }
    
    
    public function writeSimple($items,$exportProfile)
    {
        
        foreach ($items as $item) {
            $attributeMapping = $this->connectorService->getMappingByCode($item['attribute'], self::AKENEO_ATTRIBUTE_ENTITY_NAME,$exportProfile);
            
            if ($attributeMapping) {
               
                $this->requiredApiParams = [
                                'attribute' => $attributeMapping->getExternalId(),
                                'exportProfile' => $exportProfile
                            ];


                $mapping = $this->checkMappingInDb($item,$entity = self::AKENEO_ENTITY_NAME,$exportProfile);
                
                if(!empty($mapping)) {
                    if ($this->parameters->has('switchForUpdate') && $this->parameters->get('switchForUpdate')) {
                        $updateTrack = $this->connectorService->getEntityTrackByEntityAndCode(self::AKENEO_ENTITY_NAME, $item['code']);
                        
                        if (!$updateTrack) {
                            $this->stepExecution->incrementSummaryInfo('update');
                            continue;
                        }
                    }

                    $result = $this->connectorService->requestApiAction(
                        self::ACTION_UPDATE, 
                        $this->formatData($item),
                        array_merge(
                            $this->requiredApiParams,
                            [ 
                            'id' => $mapping->getExternalId(),
                            ]
                        )
                    ); 
                    $this->handleAfterApiRequest($item, $result, $mapping);
                    if(isset($updateTrack)) {
                        $this->connectorService->removeTrack($updateTrack);
                        
                    }
                    $this->stepExecution->incrementSummaryInfo('update');
                } else {    
                    
                    $result = $this->connectorService->requestApiAction(
                        'addOption', 
                        $this->formatData($item), 
                        $this->requiredApiParams
                    );

                    if ($result['code'] == Response::HTTP_OK || $result['code'] == Response::HTTP_CREATED) {
                        $result['attr_id'] = (string) $attributeMapping->getExternalId();
                    }

                    $this->handleAfterApiRequest($item, $result,$mapping=null);
                    $this->stepExecution->incrementSummaryInfo('write');
                }

                /* increment write count */
                
            } 
            else {
                $this->stepExecution->incrementSummaryInfo('skipped');
            }
        }
    }

    public function updateData($item,$requiredApiParams,$id)
    {
        $result = $this->connectorService->requestApiAction(
            self::ACTION_UPDATE, 
            $this->formatData($item),
            array_merge(
                $requiredApiParams,
                [ 
                'id' => $id,
                ]
            )
        );
       
        return $result;
        
    }

    protected function formatData($item)
    {
        $formatted = [
            'name' => !empty($item['labels'][$this->getDefaultLanguage()]) ?  $item['labels'][$this->getDefaultLanguage()] : reset($item['labels']),
            'slug' => $item['code'],
        ];

        if(empty($formatted['name']) || gettype($formatted['name']) !== 'string') {
            $formatted['name'] = $item['code'];
        }        

        return $formatted;
    }
    
    public function filterDublicateValue($checkDublicateNames)
    {
        foreach($checkDublicateNames as $name) {
            if($name > 1){
                return 1;
            } else {
                continue;
            }  
        }

        return null;
    }

}