<?php

namespace Webkul\WooCommerceBundle\Connector\Writer;

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 attributes to WooCommerce
 *
 * @author    Webkul Software Pvt Ltd
 * @copyright 2010-2017 Webkul pvt. ltd.
 * @license   https://store.webkul.com/license.html
 */
class AttributeWriter extends BaseWriter implements \ItemWriterInterface
{
    use DataMappingTrait;

    const AKENEO_ENTITY_NAME = 'attribute';
    const ACTION_ADD = 'addAttribute';
    const ACTION_UPDATE = 'updateAttribute';
    const ACTION_GET = 'getAttributes';
    const WPML_CODE_ALREADY_EXIST = 'A term with the name provided already exists with this parent.';
    const ACTION_GET_SYSTEM_STATUS = 'getSystemStatus';
    const SETTING_SECTION = 'woocommerce_connector_settings';
    const CODE_ALREADY_EXIST = 'na';
    const CODE_DUPLICATE_EXIST = 'na';
    const WPML_INVALID_CODE = 'ID not exists!';
    const CODE_NOT_EXIST = 'woocommerce_rest_term_invalid';
    const WPML_GET_DATA = 'getAttributes';
    const RELATED_INDEX = null;

    protected $reservedAttributes = ['sku'];
    protected $mappedFields;
    protected $systemStatus;
    protected $obj = '';
    protected $parameters;

    /** @var array $settings */
    protected $settings;

    /**
     * write products to WooCommerce
     */
    public function write(array $items)
    {
        
        if (!$this->parameters) {
            $this->parameters = $this->stepExecution->getJobParameters();
        }
        if (!$this->settings) {
            $this->settings = $this->connectorService->getMultiSetting('settings');
        }

        if (!$this->parameters) {
            $this->parameters = $this->stepExecution->getJobParameters();
        }
    
        $exportProfile = $this->parameters->has('exportProfile') && (!empty($this->parameters->get('exportProfile'))) ? $this->parameters->get('exportProfile') : "";
        
        if (class_exists('\Webkul\WpmlProductBundle\Connector\Writer\Attribute') && isset($settings['enable_wpml']) && $this->settings['enable_wpml'] == "on") {
            
            if ($this->obj == '') {
               
                $this->obj = new \Webkul\WpmlProductBundle\Connector\Writer\Attribute($this->connectorService);
                $this->obj->setStepExecution($this->stepExecution);
                $this->obj->writeWpml($items,$exportProfile);
                
            } else {
                
                $this->obj->writeWpml($items,$exportProfile);
            }
        } else {
           
            if (empty($this->systemStatus)) {
                $this->systemStatus = $this->connectorService->requestApiAction(
                    self::ACTION_GET_SYSTEM_STATUS,
                    [],
                    ["exportProfile" => $exportProfile]
                );
            }
            if ($this->systemStatus['code'] != "200") {
                $this->stepExecution->addWarning($this->systemStatus['code'], [], new \DataInvalidItem([json_encode($this->systemStatus)]));
                $this->stepExecution->setTerminateOnly();
            }
            $this->writeSimple($items,$exportProfile);
        }
    }

    
    public function writeSimple($items,$exportProfile)
    {
       
        if (empty($this->mappedFields)) {
            $this->mappedFields = $this->connectorService->getMultiSetting('settings');
        }
       
        foreach ($items as $item) {
            if (!array_key_exists($item['type'], $this->attributeTypes)) {
                $errorMsg = 'export not supported for ' . $item['type'];
                $this->stepExecution->incrementSummaryInfo('skipped');
                
                continue;
            } elseif (in_array($item['code'], $this->reservedAttributes) || in_array($item['code'], $this->mappedFields)) {
                $this->stepExecution->incrementSummaryInfo('skipped');
                continue;
            }



            $formattedData = $this->formatData($item,$exportProfile);
            
            $mapping = $this->checkMappingInDb($item,$entity = self::AKENEO_ENTITY_NAME,$exportProfile);

            if ($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,
                    $formattedData,
                    ['id' => $mapping->getExternalId(),"exportProfile" => $exportProfile ]
                );
                    
                $this->handleAfterApiRequest($item, $result, $mapping);
                $this->stepExecution->incrementSummaryInfo('update');
                
                if (isset($updateTrack)) {
                    $this->connectorService->removeTrack($updateTrack);
                    $this->stepExecution->incrementSummaryInfo('update');
                    continue;
                }

            } else {
                $result = $this->connectorService->requestApiAction(
                    self::ACTION_ADD,
                    $formattedData,
                    ["exportProfile" => $exportProfile]
                );
                
                $reresult = $this->handleAfterApiRequest($item, $result,$mapping=null);
                $this->stepExecution->incrementSummaryInfo('write');
            }

        }

        if (isset($this->settings['enableDelete']) && filter_var($this->settings['enableDelete'], FILTER_VALIDATE_BOOLEAN)) {
            $this->deleteDataMappingAndData(self::AKENEO_ENTITY_NAME,$exportProfile);
        }
    }
    protected function formatData($item,$exportProfile)
    {
        $formatted = [];

        $formatted = [
            'name' => !empty($item['labels'][$this->getDefaultLanguage()]) ?  $item['labels'][$this->getDefaultLanguage()] : $item['code'],
            'slug' => $item['code'],
            'type' => $this->attributeTypes[$item['type']],
        ];
        if (empty($formatted['name']) || gettype($formatted['name']) !== 'string') {
            $formatted['name'] = $item['code'];
        }
        return $formatted;
    }
    
    protected $attributeTypes = [
        'pim_catalog_identifier'    => 'select',
        'pim_catalog_text'          => 'select',
        'pim_catalog_number'        => 'select',
        'pim_catalog_textarea'      => 'select',
        'pim_catalog_date'          => 'select',
        'pim_catalog_boolean'       => 'select',
        'pim_catalog_multiselect'   => 'select',
        'pim_catalog_simpleselect'  => 'select',
        'pim_catalog_metric'        => 'select',

        'pim_catalog_price_collection' => 'select',
        'pim_catalog_file'          => 'select'
        // 'pim_catalog_image'         => 'media_image',
        // 'pim_catalog_file'          => 'media_image'
    ];
}
