<?php

namespace Webkul\WooCommerceBundle\Traits;

use Webkul\WooCommerceBundle\Entity\DataMapping;
use Symfony\Component\HttpFoundation\Response;

/**
* data mapping
*/
trait DataMappingTrait
{
    protected function getDefaultLanguage()
    {  
        try {
            if (isset($this->stepExecution->getJobParameters()->get('filters')['structure']['locale'])) {
                $locales = $this->stepExecution->getJobParameters()->get('filters')['structure']['locale'];
            } else {
                $locales = $this->stepExecution->getJobParameters()->get('filters')[0]['context']['locale'];
            }
        } catch (\Exception $e) {
            $locales = '';
        } 
        if (is_array($locales)) {
            return reset($locales);
        }
        
        return $locales;
    }

    protected function getDefaultCurrency()
    {
        try {
            if (isset($this->stepExecution->getJobParameters()->get('filters')['structure']['currency'])) {
                $currency = $this->stepExecution->getJobParameters()->get('filters')['structure']['currency'];
            } else {
                $currency = $this->connectorService->getQuickSettingCurrency();
            }
        } catch (\Exception $e) {
            $currency = '';
        }

        return $currency;
    }

    protected function getDefaultScope()
    {
        try {
            if (isset($this->stepExecution->getJobParameters()->get('filters')['structure']['scope'])) {
                $scope = $this->stepExecution->getJobParameters()->get('filters')['structure']['scope'];
            } else {
                $scope = $this->stepExecution->getJobParameters()->get('filters')[0]['context']['scope'];
            }
        } catch (\Exception $e) {
            $scope = '';
        }

        return $scope;
    }

 
    protected function checkMappingInDb($item, $entity = self::AKENEO_ENTITY_NAME,$exportProfile)
    {
        
        $code = array_key_exists('code', $item) ? $item['code'] : null;
       // $settings = $this->connectorService->getSettings('settings');
        if ($code) {
          return $this->connectorService->getMappingByCode($code, $entity, $exportProfile);
        }
    }


    protected function checkWpmlMappingInDb($item, $rid = null, $entity = self::AKENEO_ENTITY_NAME)
    {
        $code = array_key_exists('code', $item) ? $item['code'] : null;
        $params = $this->stepExecution->getJobParameters()->all();
        $exportProfile = (!empty($params['exportProfile'])) ? $params['exportProfile'] : "";
       // $settings = $this->connectorService->getSettings('settings');
        if ($code || $code !='') {
            if ($rid) {
                return $this->connectorService->getMappingByCodeAndRelatedID($code, $entity, $rid, $exportProfile);
            } else {
                return $this->connectorService->getAllMappingByCode($code, $entity, $exportProfile);
            }
        }
    }

    protected function createOptions($code, $item, $locale = null)
    {
        $params = $this->stepExecution->getJobParameters()->all();
        $exportProfile = (!empty($params['exportProfile'])) ? $params['exportProfile'] : "";
        $attributeMapping = $this->connectorService->getMappingByCode($code, 'attribute', $exportProfile);
        $itemDatas = $item['values'][$code];
        
        if ($attributeMapping) {
            $attributeId= [
                'attribute' => $attributeMapping->getExternalId()
            ];
        
        
            foreach ($itemDatas as $itemData) {
                if ($this->connectorService->checkLocale($code) === true) {
                    if ($itemData['locale'] == $locale) {
                        $value = $itemData["data"];
                    }
                } else {
                    $value = $itemData["data"];
                }
            }

            if ($value && !is_array($value)) {
                if (in_array($code, $this->connectorService->getFileAttributeCodes())) {
                    $value = $this->connectorService->generateFileUrl($value);
                    
                    $formatted = [
                        'name' => $value,
                        'slug' => $this->connectorService->convertToCode($value),
                    ];
                } else {
                    $formatted = [
                        'name' => $value,
                        'slug' => $this->connectorService->convertToCode($value),
                    ];
                }
            } elseif ($value) {
                if (in_array($code, $this->connectorService->getPriceAttributeCodes())) {
                    foreach ($value as $key => $avalue) {
                        if ($avalue['currency'] = $this->getDefaultCurrency()) {
                            $value = $avalue['amount']." ".$avalue['currency'];
                            $formatted = [
                                'name' => $value,
                                'slug' => $this->connectorService->convertToCode($value),
                            ];
                        }
                    }
                } else {
                    $settings = $this->connectorService->getMultiSetting('settings');
                    
                    if (isset($settings['enableUnit']) == "on") {
                        $value = $value['amount']." ".$value['unit'];
                        $formatted = [
                            'name' => $value,
                            'slug' => $this->connectorService->convertToCode($value),
                        ];
                    } else {
                        $value = !empty($value['amount']) ? $value['amount'] : null;
                        $formatted = [
                            'name' => $value,
                            'slug' => $this->connectorService->convertToCode($value),
                        ];
                    }
                }
            }
            

            $vItem['code'] = $value;
            $mapping = $this->checkMappingInDb($vItem, 'option', $exportProfile);
            
            if ($mapping) {
                $result = $this->connectorService->requestApiAction(
                    self::ACTION_UPDATE,
                    $formatted,
                    array_merge(
                        $attributeId,
                        [
                        'id' => $mapping->getExternalId(),
                        'exportProfile' => $exportProfile
                        ]
                    )
                );
                $this->handleAttributeOption($vItem, $result, $mapping);
            } else {
                $result = $this->connectorService->requestApiAction(
                    'addOption',
                    $formatted,
                    array_merge(
                        $attributeId,
                        ['exportProfile' => $exportProfile]
                    )
                );
                $this->handleAttributeOption($vItem, $result);
            }
        }
        return 1;
    }

    
    public function handleAttributeOption($vItem, $result, DataMapping $mapping = null)
    {
        $resourceId = !empty($result['id']) ? $result['id'] : null;
        $params = $this->stepExecution->getJobParameters()->all();
        $exportProfile = (!empty($params['exportProfile'])) ? $params['exportProfile'] : "";        
        if ($resourceId) {
            $this->connectorService->addOrUpdateMapping(
                $mapping,
                $vItem['code'],
                'option',
                $resourceId,
                $exportProfile,
                self::RELATED_INDEX && !empty($result[self::RELATED_INDEX]) ? $result[self::RELATED_INDEX] : null
            );

            return $result;
        }
        return null;
    }

    protected function handleDelete($mappings)
    {
        $params = $this->stepExecution->getJobParameters()->all();
        $exportProfile = (!empty($params['exportProfile'])) ? $params['exportProfile'] : "";        
        foreach ($mappings as $mapping) {
            $this->connectorService->requestApiAction(
                self::ACTION_DELETE,
                '',
                ['id' => $mapping->getExternalId(),'force' => true, 'exportProfile' => $exportProfile]
            );
            $this->connectorService->deleteMapping($mapping);
        }
    }

    protected function searchByslug($item, $requiredApiParams)
    {
        $index = 0;
        $params = $this->stepExecution->getJobParameters()->all();
        $exportProfile = (!empty($params['exportProfile'])) ? $params['exportProfile'] : ""; 
        $allResults = $this->connectorService->requestApiAction(
            self::WPML_GET_DATA,
            [],
            array_merge(
                $this->requiredApiParams,
                ['search' => $item['code'], 'exportProfile' => $exportProfile]
            )
        );
       
        if (sizeof($allResults)>1) {
            $realResult = $allResults[$index];
            
            return $realResult;
        }
        
        return null;
    }

    

    
    protected function handleAfterApiRequest($item, $result, DataMapping $mapping = null)
    {
       
        if ($this->getJobName() == 'woocommerce_quick_export') {
           
            $exportProfile1 = $this->connectorService->getDefaultCredential() ? $this->connectorService->getDefaultCredential()->getId() : '';
            $exportProfile = strval($exportProfile1);
            
        } else {
            $params = $this->stepExecution->getJobParameters()->all();
            $exportProfile = (!empty($params['exportProfile'])) ? $params['exportProfile'] : "";
        }
        
        
        $code = !empty($result['code']) ? $result['code'] : 0;
        
        $requiredParams = !empty($this->requiredApiParams) ? $this->requiredApiParams : [];
        $requiredParams['exportProfile'] = $exportProfile;
        
        switch ($code) {
            case self::CODE_DUPLICATE_EXIST:
                if ($mapping) {
                    $this->connectorService->deleteMapping(
                        $mapping
                    );
                    $mapping = null;
                }

            case self::CODE_NOT_EXIST:
                $reResult = $this->connectorService->requestApiAction(
                    self::ACTION_ADD,
                    $this->formatData($item,$exportProfile),
                    $requiredParams
                );

                if (!empty($reResult['code']) && ($reResult['code'] === 200 || $reResult['code'] === 201)) {
                    $resourceId = !empty($reResult['id']) ? $reResult['id'] : null;
                } elseif (!empty($reResult['code']) && $reResult['code'] == self::CODE_ALREADY_EXIST) {
                    $resourceId = !empty($reResult['data']['resource_id']) ? $reResult['data']['resource_id'] : null;
                }
                if ($mapping && !empty($resourceId)) {
                    $this->connectorService->addOrUpdateMapping(
                        $mapping,
                        $item['code'],
                        self::AKENEO_ENTITY_NAME,
                        $resourceId,
                        $exportProfile,
                        self::RELATED_INDEX && !empty($reResult[self::RELATED_INDEX]) ? $reResult[self::RELATED_INDEX] : null,
                        $this->stepExecution->getJobExecution()->getId()
                    );
                    

                    $images = !empty($reResult['images']) ? $reResult['images'] :null;
                    
                    if ($images) {
                        foreach ($images as $image) {
                            $imageId = !empty($image['id']) ? $image['id'] : null;
                            if ($imageId) {
                                $code = $item['code'].'-'.$image['name'];
                                $imageMapping = $this->connectorService->getMappingByCode($code, "image", $exportProfile);
                                $this->connectorService->addOrUpdateMapping(
                                        $imageMapping,
                                        $code,
                                        "image",
                                        $imageId,
                                        $exportProfile,
                                        '',
                                        $this->stepExecution->getJobExecution()->getId()
                                    );
                            }
                        }
                    }
                    $image = !empty($reResult['image']) ? $reResult['image'] :null;
                    if ($image) {
                        $imageId = !empty($image['id']) ? $image['id'] : null;

                        if ($imageId) {
                            $code = $item['code'].'-'.$image['title'];
                            $imageMapping = $this->connectorService->getMappingByCode($code, "image", $exportProfile);
                            $this->connectorService->addOrUpdateMapping(
                                    $imageMapping,
                                    $code,
                                    "image",
                                    $imageId,
                                    $exportProfile,
                                    '',
                                    $this->stepExecution->getJobExecution()->getId()
                                );
                        }
                    }
                    $image = !empty($reResult['image']) ? $reResult['image'] :null;
                    
                    if ($image) {
                        $imageId = !empty($image['id']) ? $image['id'] : null;
                            
                        if ($imageId) {
                            $code = $item['code'].'-'.$image['title'];
                            $imageMapping = $this->connectorService->getMappingByCode($code, "image", $exportProfile);
                                
                            $this->connectorService->addOrUpdateMapping(
                                    $imageMapping,
                                    $code,
                                    "image",
                                    $imageId,
                                    $exportProfile,
                                    '',
                                    $this->stepExecution->getJobExecution()->getId()
                                );
                        }
                    }
                        
                    return $reResult;
                }
                // no break
            case self::CODE_ALREADY_EXIST:
                
                $resourceId = !empty($result['data']['resource_id']) ? $result['data']['resource_id'] : null;
                
                if ($resourceId) {
                    $reResult = $this->connectorService->requestApiAction(
                        self::ACTION_UPDATE,
                        $this->formatData($item,$exportProfile),
                        array_merge($requiredParams, [ 'id' => $resourceId ])
                    );
                        
                    if (!self::RELATED_INDEX || isset($reResult[self::RELATED_INDEX])) {
                        $this->connectorService->addOrUpdateMapping(
                            $mapping,
                            $item['code'],
                            self::AKENEO_ENTITY_NAME,
                            $resourceId,
                            $exportProfile,
                            self::RELATED_INDEX  ? $reResult[self::RELATED_INDEX] : null,
                            $this->stepExecution->getJobExecution()->getId()
                        );
                    }
                    $images = !empty($reResult['images']) ? $reResult['images'] :null;
                    if ($images) {
                        foreach ($images as $image) {
                            $imageId = !empty($image['id']) ? $image['id'] : null;

                            if ($imageId) {
                                $code = $item['code'].'-'.$image['name'];
                                $imageMapping = $this->connectorService->getMappingByCode($code, "image", $exportProfile);
                                $this->connectorService->addOrUpdateMapping(
                                        $imageMapping,
                                        $code,
                                        "image",
                                        $imageId,
                                        $exportProfile,
                                        '',
                                        $this->stepExecution->getJobExecution()->getId()
                                    );
                            }
                        }
                    }
                    $image = !empty($reResult['image']) ? $reResult['image'] :null;
                    
                    if ($image) {
                        $imageId = !empty($image['id']) ? $image['id'] : null;
                            
                        if ($imageId) {
                            $code = $item['code'].'-'.$image['title'];
                            $imageMapping = $this->connectorService->getMappingByCode($code, "image", $exportProfile);
                                
                            $this->connectorService->addOrUpdateMapping(
                                    $imageMapping,
                                    $code,
                                    "image",
                                    $imageId,
                                    $exportProfile,
                                    '',
                                    $this->stepExecution->getJobExecution()->getId()
                                );
                        }
                    }
                    return $reResult;
                }
                break;
            
            case 'woocommerce_rest_cannot_create':
            case 'woocommerce_rest_cannot_edit':
                if (!empty(self::ACTION_GET)) {
                    static $allResults;
                    if (empty($allResults)) {
                        $allResults = $this->connectorService->requestApiAction(
                            self::ACTION_GET,
                            [],
                            ['search' => $item['code'], 'exportProfile' => $exportProfile]
                        );
                    }
                    foreach ($allResults as $key => $result) {
                        if (is_array($result) && !empty($result['slug']) && !empty($result['id'])) {
                            if ($result['slug'] == $item['code'] || $result['slug'] == 'pa_' . $item['code']) {
                                $this->connectorService->addOrUpdateMapping(
                                    $mapping,
                                    $item['code'],
                                    self::AKENEO_ENTITY_NAME,
                                    $result['id'],
                                    $exportProfile,
                                    self::RELATED_INDEX ? $reResult[self::RELATED_INDEX] : null,
                                    $this->stepExecution->getJobExecution()->getId()
                                );

                                $images = !empty($result['images']) ? $result['images'] :null;
                                if ($images) {
                                    foreach ($images as $image) {
                                        $imageId = !empty($image['id']) ? $image['id'] : null;

                                        if ($imageId) {
                                            $code = $item['code'].'-'.$image['name'];
                                            $imageMapping = $this->connectorService->getMappingByCode($code, "image", $exportProfile);
                                            $this->connectorService->addOrUpdateMapping(
                                                $imageMapping,
                                                $code,
                                                "image",
                                                $imageId,
                                                $exportProfile,
                                                '',
                                                $this->stepExecution->getJobExecution()->getId()
                                            );
                                        }
                                    }
                                }
                                $image = !empty($result['image']) ? $result['image'] :null;
                    
                                if ($image) {
                                    $imageId = !empty($image['id']) ? $image['id'] : null;
                                    
                                    if ($imageId) {
                                        $code = $item['code'].'-'.$image['title'];
                                        $imageMapping = $this->connectorService->getMappingByCode($code, "image", $exportProfile);
                                        
                                        $this->connectorService->addOrUpdateMapping(
                                            $imageMapping,
                                            $code,
                                            "image",
                                            $imageId,
                                            $exportProfile,
                                            '',
                                            $this->stepExecution->getJobExecution()->getId()
                                        );
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                break;
            case 'woocommerce_rest_product_invalid_id':
            case 'woocommerce_rest_taxonomy_invalid':
                if ($mapping) {
                    $this->connectorService->deleteMapping(
                        $mapping
                    );
                    $mapping = null;
                }
                $result = $this->connectorService->requestApiAction(
                    self::ACTION_ADD,
                    $this->formatData($item,$exportProfile),
                    array_merge($requiredParams)
                );

                // no break
            case Response::HTTP_OK:
            case Response::HTTP_CREATED:
                
                    
                    $resourceId = !empty($result['id']) ? $result['id'] : null;
                    
                    if ($resourceId) {
                        
                        $this->connectorService->addOrUpdateMapping(
                            $mapping,
                            $item['code'],
                            self::AKENEO_ENTITY_NAME,
                            $resourceId,
                            $exportProfile,
                            self::RELATED_INDEX && !empty($result[self::RELATED_INDEX]) ? $result[self::RELATED_INDEX] : null,
                            $this->stepExecution->getJobExecution()->getId()
                        );
                        
                    }
                    
                    $images = !empty($result['images']) ? $result['images'] :null;
                    
                    if ($images) {
                        
                        
                        foreach ($images as $image) {
                            $imageId = !empty($image['id']) ? $image['id'] : null;
                            
                            if ($imageId) {
                                $code = $item['code'].'-'.$image['name'];
                                
                                $imageMapping = $this->connectorService->getMappingByCode($code, "image", $exportProfile);
                                
                                $this->connectorService->addOrUpdateMapping(
                                    $imageMapping,
                                    $code,
                                    "image",
                                    $imageId,
                                    $exportProfile,
                                    '',
                                    $this->stepExecution->getJobExecution()->getId()
                                );
                            }
                        }
                    }
                    
                    $image = !empty($result['image']) ? $result['image'] :null;
                    
                        if ($image) {
                            $imageId = !empty($image['id']) ? $image['id'] : null;
                            
                            if ($imageId) {
                                $code = $item['code'].'-'.$image['yt'];
                                $imageMapping = $this->connectorService->getMappingByCode($code, "image", $exportProfile);
                                
                                $this->connectorService->addOrUpdateMapping(
                                    $imageMapping,
                                    $code,
                                    "image",
                                    $imageId,
                                    $exportProfile,
                                    '',
                                    $this->stepExecution->getJobExecution()->getId()
                                );
                            }
                        }

                    return $result;
                break;
            case 'woocommerce_product_image_upload_error':
                if (!empty($item['code'])) {
                   
                    $this->stepExecution->addWarning($result['message'] .'at line' .__LINE__, [], new \DataInvalidItem(['code' => $item['code'] ]));
                    
                }
                break;
            case 'woocommerce_rest_authentication_error':
                if (!empty($result['message'])) {
                    $this->stepExecution->addWarning($result['message'], [], new \DataInvalidItem([]));
                }
                break;
            case 'woocommerce_product_invalid_image_id':
                $getResult = explode(" ", $result["message"]);
                $getResult = reset($getResult);
                $imageId = (int)str_replace("#", "", $getResult);
                $mappingToRemove = $this->connectorService->getMappingByExternalId($imageId,'image', $exportProfile);
                $this->connectorService->deleteMapping($mappingToRemove);
                if($mapping) {
                    $result = $this->connectorService->requestApiAction(
                        self::ACTION_UPDATE,
                        $this->formatData($item,$exportProfile),
                        ['id' => $mapping->getExternalId(), 'exportProfile' => $exportProfile]
                    );
                } else {
                    $result = $this->connectorService->requestApiAction(
                        self::ACTION_ADD,
                        $this->formatData($item,$exportProfile),
                        ['exportProfile' => $exportProfile]
                    );
                }
                
                $this->handleAfterApiRequest($item, $result, $mapping);
                break;
            
        }
    }

    protected function handleAfterWPMLApiRequest($item, $result, DataMapping $mapping = null)
    {
        $this->stepExecution->incrementSummaryInfo('write');
        $code = !empty($result['code']) ? $result['code'] : 0;
        $params = $this->stepExecution->getJobParameters()->all();
        $exportProfile = (!empty($params['exportProfile'])) ? $params['exportProfile'] : "";
        $requiredParams = !empty($this->requiredApiParams) ? $this->requiredApiParams : [];
        $settings = $this->connectorService->getMultiSetting('settings');
        $exportedLocales = $this->connectorService->getQuickSettingLocales();
        $mappingWpml = $this->checkWpmlMappingInDb($item);
        
        
        if (array_key_exists('Error', $result)) {
            $code = $result['Error'];
        } elseif (array_key_exists('message', $result) && $result['message'] == "Empty Term.") {
            $code = $result['code'];
        }
        if (self::AKENEO_ENTITY_NAME == "attribute") {
            if (isset($result[0]['error_data'])) {
                if (key($result[0]['error_data'])=="invalid_product_attribute_slug_already_exists") {
                    $code = "woocommerce_rest_cannot_create";
                }
            }
        }

        
        switch ($code) {
            case "woocommerce_rest_cannot_create":
            case self::WPML_CODE_ALREADY_EXIST:
                $allResults = $this->connectorService->requestWpmlApiAction(
                    self::WPML_GET_DATA,
                    [],
                    array_merge(
                        $requiredParams,
                        [
                            'slug' => $item['code'],
                        ]
                    )
                );
                
                unset($allResults['code']);
                if (self::AKENEO_ENTITY_NAME == "attribute") {
                    if (isset($allResults['id'])) {
                        $this->connectorService->addOrUpdateWPMLMapping(
                            $mapping,
                            $item['code'],
                            self::AKENEO_ENTITY_NAME,
                            $allResults['id'],
                            $exportProfile
                        );
                    }
                } elseif (self::AKENEO_ENTITY_NAME == "option") {
                    foreach ($allResults as $allresult) {
                        $translatedlanguage = $allresult['translated_language_code'] ?? null;
                        $langLabel = !empty($item['labels'][$translatedlanguage]) ?  $item['labels'][$translatedlanguage] : reset($item['labels']);
                        if (isset($allresult['id'])) {
                            $this->connectorService->addOrUpdateWPMLMapping(
                                $mapping,
                                $item['code'],
                                self::AKENEO_ENTITY_NAME,
                                $allresult['id'],
                                $exportProfile,
                                $translatedlanguage,
                                $allresult['slug'],
                                $langLabel
                            );
                        }
                    }
                    return 1;
                } else {
                    $newResult = [];
                    foreach ($allResults as $allresult) {
                        $translatedlanguage = $allresult['translated_language_code'] ?? null;
                        if (isset($allresult['id'])) {
                            $this->connectorService->addOrUpdateWPMLMapping(
                                $mapping,
                                $item['code'],
                                self::AKENEO_ENTITY_NAME,
                                $allresult['id'],
                                $exportProfile,
                                $translatedlanguage
                            );
                            $newResult[$translatedlanguage] = $allresult['id'];
                        }
                    }
                    
                    return $newResult;
                }
                
                break;
            
            case self::WPML_INVALID_CODE:
                
                $exportedLocales = $this->connectorService->getQuickSettingLocales();
                if ($mappingWpml) {
                    foreach ($mappingWpml as $mapping) {
                        if ($mapping) {
                            $this->connectorService->deleteMapping(
                                $mapping
                            );
                        }
                    }
                }
                $formattedData = $this->formatWpmlData($item, $exportedLocales);
                
                $reresult = $this->connectorService->requestWpmlApiAction(
                    self::ACTION_ADD,
                    $formattedData,
                    $requiredParams
                );
                
                $preresult = $this->handleAfterWPMLApiRequest($item, $reresult);
                
                return $preresult;
                break;
            
            case Response::HTTP_OK:
            case Response::HTTP_CREATED:
                   
                    $language = !empty($result['rid']) ? $result['rid'] : null;
                    
                    if ($language) {
                        $resourceId = !empty($result['id']) ? $result['id'] : null;
                        if ($resourceId) {
                            $this->connectorService->addOrUpdateWPMLMapping(
                                $mapping,
                                $item['code'],
                                self::AKENEO_ENTITY_NAME,
                                $resourceId,
                                $exportProfile,
                                $language
                            );
                        }
                    } else {
                        if (self::AKENEO_ENTITY_NAME == "option") {
                            unset($result['code']);
                            $label = [];
                            
                            foreach ($item['labels'] as $key=>$val) {
                                if (in_array($key, $exportedLocales)) {
                                    $label[] = $key;
                                }
                            }
                            foreach ($result as $key =>$data) {
                                $resourceId = $data['id'];
                                $slug = $data['slug'];
                                
                                if ($resourceId) {
                                    if (!empty($mappingWpml)) {
                                        $mapping = $this->connectorService->getMappingByCodeAndRelatedID($item['code'], self::AKENEO_ENTITY_NAME, $label[$key]);
                                    }
                                    $langCode = $label[$key];
                                    $langLabel = !empty($item['labels'][$langCode]) ?  $item['labels'][$langCode] : reset($item['labels']);
                                    $this->connectorService->addOrUpdateWPMLMapping(
                                        $mapping,
                                        $item['code'],
                                        self::AKENEO_ENTITY_NAME,
                                        $resourceId,
                                        $exportProfile,
                                        $label[$key],
                                        $slug,
                                        $langLabel
                                    );
                                }
                            }
                        } else {
                            unset($result['code']);
                            $label = [];
                            
                            foreach ($item['labels'] as $key=>$val) {
                                if (in_array($key, $exportedLocales)) {
                                    $label[] = $key;
                                }
                            }
                        
                            foreach ($result as $key => $resourceId) {
                                if ($resourceId) {
                                    if (!empty($mappingWpml)) {
                                        $mapping = $this->connectorService->getMappingByCodeAndRelatedID($item['code'], self::AKENEO_ENTITY_NAME, $label[$key]);
                                    }
                                        
                                    $this->connectorService->addOrUpdateWPMLMapping(
                                            $mapping,
                                            $item['code'],
                                            self::AKENEO_ENTITY_NAME,
                                            $resourceId,
                                            $exportProfile,
                                            $label[$key]
                                        );
                                }
                            }
                        }
                    }
                    
                return array_combine($label, $result);
                break;
            case 'woocommerce_product_image_upload_error':
                if (!empty($item['code'])) {
                    $this->stepExecution->addWarning("can't upload images to woocommerce", [], new \DataInvalidItem(['code' => $item['code'] ]));
                }
                break;
            case 'woocommerce_rest_authentication_error':
                if (!empty($result['message'])) {
                    $this->stepExecution->addWarning($result['message'], [], new \DataInvalidItem([]));
                    $this->stepExecution->setTerminateOnly();
                }
                break;
            case 0:
            default:
                if (!empty($item['code'])) {
                    $arr = [
                        'code' => $item['code']
                    ];
                } else {
                    $arr = [];
                }
                $this->stepExecution->addWarning(json_encode($result), [], new \DataInvalidItem($arr));
        }
    }

    protected function deleteDataMappingAndData($entity,$exportProfile)
    {
        $trackers = $this->connectorService->getEntityTrackByEntity($entity,$exportProfile);
        
        if ($trackers) {
            foreach ($trackers as $tracker) {
                $mappings = $this->connectorService->getAllMappingByCode($tracker->getCode(), $entity, $exportProfile);
               
                if ($mappings) {
                    switch ($entity) {
                        case 'category':
                            
                            foreach ($mappings as $mapping) {
                                $result = $this->connectorService->requestApiAction(
                                    'deleteCategory',
                                    '',
                                    ['id' => $mapping->getExternalId(),'force' => true, 'exportProfile' => $exportProfile]
                                );
                                $this->connectorService->deleteMapping($mapping);
                            }
                            break;
                        case 'attribute':
                            foreach ($mappings as $mapping) {
                                $result = $this->connectorService->requestApiAction(
                                    'deleteAttribute',
                                    '',
                                    ['id' => $mapping->getExternalId(),'force' => true, 'exportProfile' => $exportProfile]
                                );
                                if ($result["code"] == "200") {
                                    $this->connectorService->deleteMapping($mapping);
                                }
                            }
                            break;

                        case 'option':
                            foreach ($mappings as $mapping) {
                                if ($mapping->getRelatedId()) {
                                    $requiredApiParams = [
                                        'attribute' => $mapping->getRelatedId()
                                    ];

                                    $result = $this->connectorService->requestApiAction(
                                        'deleteAttributeOptions',
                                        '',
                                        array_merge(
                                            $requiredApiParams,
                                            ['id' => $mapping->getExternalId(),'force' => true, 'exportProfile' => $exportProfile]
                                        )
                                    );
                                    if ($result["code"] == "200") {
                                        $this->connectorService->deleteMapping($mapping);
                                    }
                                }
                            }
                            break;
                        case 'product':
                        case 'product-model':
                            foreach ($mappings as $mapping) {
                                $this->connectorService->requestApiAction(
                                    'deleteProduct',
                                    '',
                                    ['id' => $mapping->getExternalId(),'force' => true, 'exportProfile' => $exportProfile]
                                );
                                $this->connectorService->deleteMapping($mapping);
                            }
                            break;
                        default:
                            break;
                    }
                    $this->connectorService->removeTrack($tracker);
                }
            }
        }
        return 1;
    }
}
