<?php

namespace Webkul\WooCommerceBundle\Connector\Writer;

use Webkul\WooCommerceBundle\Traits\DataMappingTrait;
use Webkul\WooCommerceBundle\Listener\ClassDefinationForCompatibility;

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


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

    const AKENEO_ENTITY_NAME = 'category';
    const ACTION_ADD = 'addCategory';
    const ACTION_UPDATE = 'updateCategory';
    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 = 'parent';
    const WPML_CODE_ALREADY_EXIST = 'A term with the name provided already exists with this parent.';
    const WPML_GET_DATA = 'getCategory';
    const WPML_INVALID_CODE = 'invalid_term';
    const ACTION_GET = '';
    const ACTION_GET_SYSTEM_STATUS = 'getSystemStatus';

    protected $obj = '';
    protected $parameters;

    /**
     * write products to WooCommerce.
     */
    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');

       
        if (class_exists('Webkul\WpmlProductBundle\Connector\Writer\Category') && isset($settings['enable_wpml']) && $settings['enable_wpml'] == 'on') {
            if ($this->obj == '') {
                $this->obj = new \Webkul\WpmlProductBundle\Connector\Writer\Category($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)
    {
       
        $settings = $this->connectorService->getMultiSetting('settings');
        foreach ($items as $item) {
            if (empty($item['parent'])) {
                continue;
            }
            
            $mapping = $this->checkMappingInDb($item,$entity = self::AKENEO_ENTITY_NAME,$exportProfile);
            $formattedData = $this->formatData($item,$exportProfile);
            
            if (empty($formattedData)) {
                continue;
            }

            if (empty($formattedData['name'])) {
               
                $this->stepExecution->addWarning('label not found for this  category', [], new \DataInvalidItem(['code' => $item['code']]));
                $this->stepExecution->incrementSummaryInfo('skipped');
                continue;
            }
            
           
            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('already_exported');
                        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('already_exported');
                    continue;
                }
            } else {
                
                $result = $this->connectorService->requestApiAction(
                                self::ACTION_ADD, $formattedData,
                                ['exportProfile' => $exportProfile]

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

            /* increment write count */
            
        }
        if (isset($settings['enableDelete']) && $settings['enableDelete'] == 'on') {
            $this->deleteDataMappingAndData(self::AKENEO_ENTITY_NAME,$exportProfile);
        }
    }

    protected function formatData($item,$exportProfile)
    {
        $formatted = [
            'name' => !empty($item['labels'][$this->getDefaultLanguage()]) ? $item['labels'][$this->getDefaultLanguage()] : reset($item['labels']),
            'slug' => $item['code'],
        ];
       
        $classExist = 'Webkul\CategoryExtendBundle\CategoryExtendBundle';
        if (class_exists($classExist)) {
            if (!empty($item['image'])) {
                $url = $this->connectorService->generateImageUrl($item['image'],$exportProfile, $host = null);
                if ($url) {
                    $id = $this->checkImagesExported($item, $url,$exportProfile);
                    if ($id) {
                        $formatted['image'] = ['id' => $id];
                    } else {
                        $formatted['image'] = ['src' => $url, 'alt' => $this->getImageName($url), 'title' => $this->getImageName($url)];
                    }
                }
            }
            if (!empty($item['description'])) {
                $formatted['description'] = !empty($item['description'][$this->getDefaultLanguage()]) ? $item['description'][$this->getDefaultLanguage()] : reset($item['description']);
            }
        }

        if (!empty($item['parent'])) {
            $parentMapping = $this->connectorService->getMappingByCode($item['parent'], self::AKENEO_ENTITY_NAME,$exportProfile);
            if ($parentMapping) {
                $formatted['parent'] = $parentMapping->getExternalId();
            }
        }

        return $formatted;
    }

    public function getImageName($imageurl)
    {
        $getCode = explode('/', $imageurl);
        $code = end($getCode);
        $name = explode('_', $code);
        unset($name[0]);
        $getName = implode('_', $name);
        if ($getName) {
            return $getName;
        }

        return null;
    }

    public function checkImagesExported($item, $imageUrl,$exportProfile)
    {
        $imageName = $this->getImageName($imageUrl);
        $code = $item['code'].'-'.$imageName;
        $checkItem = $this->checkMappingInDb($item,$entity = self::AKENEO_ENTITY_NAME,$exportProfile);
        if (!$checkItem) {
            return false;
        }

        $imageMapping = $this->connectorService->getMappingByCode($code, 'image',$exportProfile);
        if (!$imageMapping) {
            return false;
        }

        return $imageMapping->getExternalId();
    }
}
