/**
  * Handles the whole import
  */
 public function import()
 {
     $this->setData();
     $this->setDetails();
     $this->setVariants();
     $this->setProperties();
     $data = $this->data;
     $data['mainDetail'] = $this->details;
     $mainDetailId = -1;
     $ArticleResource = self::getArticleApi();
     $VariantResource = self::getVariantApi();
     try {
         // If a mappings exists, it's a regular item
         $SHOPWARE_itemID = PlentymarketsMappingController::getItemByPlentyID($this->ItemBase->ItemID);
         // Should the categories be synchronized?
         if (PlentymarketsConfig::getInstance()->getItemCategorySyncActionID(IMPORT_ITEM_CATEGORY_SYNC) == IMPORT_ITEM_CATEGORY_SYNC) {
             $this->setCategories();
             $data['categories'] = $this->categories;
         }
         // Should the number be synchronized?
         // This does only matter if there are no variants
         if (PlentymarketsConfig::getInstance()->getItemNumberImportActionID(IMPORT_ITEM_NUMBER) == IMPORT_ITEM_NUMBER && !count($this->variants)) {
             // strip whitespaces
             $number = trim($this->ItemBase->ItemNo);
             // If this number does not belong to this item
             if (!PlentymarketsImportItemHelper::isNumberExistantItem($number, $SHOPWARE_itemID)) {
                 // and check if the number is valid
                 if (!PlentymarketsImportItemHelper::isNumberValid($number)) {
                     throw new PlentymarketsImportItemNumberException('The item number »' . $number . '« of item »' . $this->data['name'] . '« with the id »' . $this->ItemBase->ItemID . '« is invalid', 3120);
                 }
                 // check if the number is available anyway
                 if (PlentymarketsImportItemHelper::isNumberExistant($number)) {
                     throw new PlentymarketsImportItemNumberException('The item number »' . $number . '« of item »' . $this->data['name'] . '« with the id »' . $this->ItemBase->ItemID . '« is already in use', 3121);
                 }
                 // then update it
                 $data['mainDetail']['number'] = $number;
             }
         }
         // Update the item
         $Article = $ArticleResource->update($SHOPWARE_itemID, $data);
         // Log
         PlentymarketsLogger::getInstance()->message('Sync:Item', sprintf('The item »%s« with the number »%s« has been updated', $data['name'], $Article->getMainDetail()->getNumber()));
         // Remember the main detail's id (to set the prices)
         $mainDetailId = $Article->getMainDetail()->getId();
         // Variants that will be commited to the API
         $variants = array();
         $update = array();
         $number2sku = array();
         $keep = array('numbers' => array(), 'ids' => array());
         // Es gibt varianten
         if (count($this->variants)) {
             //
             $VariantController = new PlentymarketsImportItemVariantController($this->ItemBase);
             // Counter
             $numberOfVariantsUpdated = 0;
             $numberOfVariantsCreated = 0;
             $numberOfVariantsDeleted = 0;
             foreach ($this->variants as $variantId => $variant) {
                 // Directly add the prices
                 $PlentymarketsImportEntityItemPrice = new PlentymarketsImportEntityItemPrice($this->ItemBase->PriceSet, $VariantController->getMarkupByVariantId($variantId));
                 $variant['prices'] = $PlentymarketsImportEntityItemPrice->getPrices();
                 // If the variant has an id, it is already created and mapped soo we just keep it
                 if (array_key_exists('id', $variant)) {
                     ++$numberOfVariantsUpdated;
                     $keep['ids'][] = $variant['id'];
                 } else {
                     ++$numberOfVariantsCreated;
                     $variant['configuratorOptions'] = $VariantController->getOptionsByVariantId($variantId);
                     $keep['numbers'][] = $variant['number'];
                     // Internal mapping of the variant number to some plenty information
                     $number2sku[$variant['number']] = $variant['X_plentySku'];
                 }
                 $variants[] = $variant;
             }
             // The configurator set has to be adapted
             $update['configuratorSet'] = array('groups' => $VariantController->getGroups());
             // Delete all variants
             if ($numberOfVariantsUpdated == 0) {
                 $Article = $ArticleResource->update($SHOPWARE_itemID, array('configuratorSet' => array('groups' => array()), 'variations' => array()));
             }
             $update['variants'] = $variants;
             // Check if the main detail will be deleted
             if (!in_array($mainDetailId, $keep['ids'])) {
                 // Promote the first variante to be the main detail
                 $update['variants'][0]['isMain'] = true;
                 $deleteMainVariant = true;
             } else {
                 $deleteMainVariant = false;
             }
             $ArticleResource->update($SHOPWARE_itemID, $update);
             // Check if the main detail will be deleted
             if ($deleteMainVariant) {
                 // If the main detail is not needed anymore, delete it right away
                 // Otherwise it will be a dead data record. The main details are not
                 // returned from the API->getOne call. Only the "real" main detail.
                 Shopware()->Models()->remove(Shopware()->Models()->find('Shopware\\Models\\Article\\Detail', $mainDetailId));
                 Shopware()->Models()->flush();
                 PlentymarketsMappingController::deleteItemVariantByShopwareID($mainDetailId);
                 ++$numberOfVariantsDeleted;
             }
             $article = $ArticleResource->getOne($SHOPWARE_itemID);
             // Add the main detail
             $article['details'][] = $article['mainDetail'];
             // Mapping for the variants
             foreach ($article['details'] as $detail) {
                 // If the variant is not needed anymore - delete it
                 if (!in_array($detail['number'], $keep['numbers']) && !in_array($detail['id'], $keep['ids'])) {
                     ++$numberOfVariantsDeleted;
                     $VariantResource->delete($detail['id']);
                     PlentymarketsMappingController::deleteItemVariantByShopwareID($detail['id']);
                 } else {
                     if (isset($number2sku[$detail['number']])) {
                         // Add the mapping
                         PlentymarketsMappingController::addItemVariant($detail['id'], $number2sku[$detail['number']]);
                     }
                 }
             }
             $VariantController->map($article);
             $messages = array();
             // Log
             if ($numberOfVariantsUpdated == 1) {
                 $messages[] = '1 variant has been updated';
             } else {
                 if ($numberOfVariantsUpdated > 1) {
                     $messages[] = $numberOfVariantsUpdated . ' variants have been updated';
                 }
             }
             if ($numberOfVariantsCreated == 1) {
                 $messages[] = '1 variant has been created';
             } else {
                 if ($numberOfVariantsCreated > 1) {
                     $messages[] = $numberOfVariantsCreated . ' variants have been created';
                 }
             }
             if ($numberOfVariantsDeleted == 1) {
                 $messages[] = '1 variant has been deleted';
             } else {
                 if ($numberOfVariantsDeleted > 1) {
                     $messages[] = $numberOfVariantsDeleted . ' variants have been deleted';
                 }
             }
             if ($messages) {
                 PlentymarketsLogger::getInstance()->message('Sync:Item', implode(', ', $messages));
             }
         } else {
             // Preise eines Normalen Artikels aktualisieren
             $PlentymarketsImportEntityItemPrice = new PlentymarketsImportEntityItemPrice($this->ItemBase->PriceSet);
             $PlentymarketsImportEntityItemPrice->update($SHOPWARE_itemID);
         }
         // Bilder
         if (PlentymarketsConfig::getInstance()->getItemImageSyncActionID(IMPORT_ITEM_IMAGE_SYNC) == IMPORT_ITEM_IMAGE_SYNC) {
             $PlentymarketsImportEntityItemImage = new PlentymarketsImportEntityItemImage($this->ItemBase->ItemID, $SHOPWARE_itemID);
             $PlentymarketsImportEntityItemImage->image();
         }
     } catch (PlentymarketsMappingExceptionNotExistant $E) {
         // Set the categories no matter what
         $this->setCategories();
         $data['categories'] = $this->categories;
         // Regular item
         if (!count($this->variants)) {
             // Numbers should be synced
             if (PlentymarketsConfig::getInstance()->getItemNumberImportActionID(IMPORT_ITEM_NUMBER) == IMPORT_ITEM_NUMBER) {
                 // strip whitespaces
                 $number = trim($this->ItemBase->ItemNo);
                 // Nummer ist ungültig oder in Benutzung
                 if (!PlentymarketsImportItemHelper::isNumberValid($number)) {
                     throw new PlentymarketsImportItemNumberException('The item number »' . $number . '« of item »' . $this->data['name'] . '« with the id »' . $this->ItemBase->ItemID . '« is invalid', 3120);
                 }
                 if (PlentymarketsImportItemHelper::isNumberExistant($number)) {
                     throw new PlentymarketsImportItemNumberException('The item number »' . $number . '« of item »' . $this->data['name'] . '« with the id »' . $this->ItemBase->ItemID . '« is already in use', 3121);
                 }
                 // Use this number
                 $data['mainDetail']['number'] = $number;
             } else {
                 // A new number is generated
                 $data['mainDetail']['number'] = PlentymarketsImportItemHelper::getItemNumber();
             }
             // Create
             $Article = $ArticleResource->create($data);
             //
             $SHOPWARE_itemID = $Article->getId();
             // Log
             PlentymarketsLogger::getInstance()->message('Sync:Item', 'The item »' . $this->data['name'] . '« has been created with the number »' . $data['mainDetail']['number'] . '«');
             // Mapping speichern
             PlentymarketsMappingController::addItem($Article->getId(), $this->ItemBase->ItemID);
             // Stock stack
             PlentymarketsImportItemStockStack::getInstance()->add($this->ItemBase->ItemID);
             // Media
             // Preise
             $PlentymarketsImportEntityItemPrice = new PlentymarketsImportEntityItemPrice($this->ItemBase->PriceSet);
             $PlentymarketsImportEntityItemPrice->update($Article->getId());
         } else {
             // Set the id of the first variant
             $mainVariant = array_shift(array_values($this->variants));
             $data['mainDetail']['number'] = $mainVariant['number'];
             // Anlegen
             $Article = $ArticleResource->create($data);
             PlentymarketsLogger::getInstance()->message('Sync:Item', 'The variant base item »' . $this->data['name'] . '« has been created created with the number »' . $data['mainDetail']['number'] . '«');
             //
             $SHOPWARE_itemID = $Article->getId();
             // Mapping speichern
             PlentymarketsMappingController::addItem($Article->getId(), $this->ItemBase->ItemID);
             $VariantController = new PlentymarketsImportItemVariantController($this->ItemBase);
             //
             $number2sku = array();
             //
             foreach ($this->variants as $variantId => &$variant) {
                 $variant['configuratorOptions'] = $VariantController->getOptionsByVariantId($variantId);
                 // Prices
                 $PlentymarketsImportEntityItemPrice = new PlentymarketsImportEntityItemPrice($this->ItemBase->PriceSet, $VariantController->getMarkupByVariantId($variantId));
                 $variant['prices'] = $PlentymarketsImportEntityItemPrice->getPrices();
                 $number2sku[$variant['number']] = $variant['X_plentySku'];
             }
             // Varianten
             $id = $Article->getId();
             $updateArticle = array('configuratorSet' => array('groups' => $VariantController->getGroups()), 'variants' => array_values($this->variants));
             PlentymarketsLogger::getInstance()->message('Sync:Item:Variant', 'Starting to create variants for the item »' . $this->data['name'] . '« with the number »' . $data['mainDetail']['number'] . '«');
             $Article = $ArticleResource->update($id, $updateArticle);
             /**@var Shopware\Models\Article\Detail $detail */
             foreach ($Article->getDetails() as $detail) {
                 // Save mapping and add the variant to the stock stack
                 $sku = $number2sku[$detail->getNumber()];
                 PlentymarketsMappingController::addItemVariant($detail->getId(), $sku);
                 PlentymarketsImportItemStockStack::getInstance()->add($sku);
             }
             $VariantController->map($ArticleResource->getOne($id));
             PlentymarketsLogger::getInstance()->message('Sync:Item:Variant', 'Variants created successfully');
         }
         // Bilder
         $PlentymarketsImportEntityItemImage = new PlentymarketsImportEntityItemImage($this->ItemBase->ItemID, $SHOPWARE_itemID);
         $PlentymarketsImportEntityItemImage->image();
     }
     // Rebuild category tree
     if (count($this->categories)) {
         /** @var \Shopware\Components\Model\CategoryDenormalization $component */
         $component = Shopware()->CategoryDenormalization();
         $component->removeArticleAssignmentments($SHOPWARE_itemID);
         foreach ($this->categories as $category) {
             $component->addAssignment($SHOPWARE_itemID, $category['id']);
         }
     }
     // Der Hersteller ist neu angelegt worden
     if ($Article instanceof Shopware\Models\Article\Article && array_key_exists('supplier', $this->data)) {
         PlentymarketsLogger::getInstance()->message('Sync:Item', 'The producer »' . $Article->getSupplier()->getName() . '« has been created');
         PlentymarketsMappingController::addProducer($Article->getSupplier()->getId(), $this->ItemBase->ProducerID);
     }
 }
 /**
  * Exports the item variants
  */
 protected function exportVariants()
 {
     // Verknüpfung mit den Attribut(-werten)
     $ConfiguratorSet = $this->SHOPWARE_Article->getConfiguratorSet();
     if (!$ConfiguratorSet instanceof Shopware\Models\Article\Configurator\Set) {
         return;
     }
     // Active the attribute values at the item --------------------------------------------------------------------
     $objectsActivateLinks = array();
     $Request_SetItemAttributeLinks = new PlentySoapRequest_SetItemAttributeLinks();
     $Request_SetItemAttributeLinks->ItemID = $this->PLENTY_itemID;
     // int
     $Request_SetItemAttributeLinks->AttributeLinks = array();
     /** @var Shopware\Models\Article\Configurator\Option $ConfiguratorOption */
     foreach ($ConfiguratorSet->getOptions() as $ConfiguratorOption) {
         $PLENTY_attributeID = PlentymarketsMappingController::getAttributeGroupByShopwareID($ConfiguratorOption->getGroup()->getId());
         $PLENTY_attributeValueID = PlentymarketsMappingController::getAttributeOptionByShopwareID($ConfiguratorOption->getId());
         $Object_AttributeLink = new PlentySoapObject_AttributeLink();
         $Object_AttributeLink->AttributeID = $PLENTY_attributeID;
         // int
         $Object_AttributeLink->AttributeValueID = $PLENTY_attributeValueID;
         // int
         $Object_AttributeLink->Activate = true;
         $objectsActivateLinks[] = $Object_AttributeLink;
     }
     // Run the calls
     foreach (array_chunk($objectsActivateLinks, 100) as $activateLinks) {
         $Request_SetItemAttributeLinks->AttributeLinks = $activateLinks;
         PlentymarketsSoapClient::getInstance()->SetItemAttributeLinks($Request_SetItemAttributeLinks);
     }
     // generate the attribute value sets --------------------------------------------------------------------------
     $objectsSetAttributeValueSets = array();
     $cacheAttributeValueSets = array();
     $Request_SetItemAttributeVariants = new PlentySoapRequest_SetItemAttributeVariants();
     $Request_SetItemAttributeVariants->ItemID = $this->PLENTY_itemID;
     // int
     $Request_SetItemAttributeVariants->SetAttributeValueSets = array();
     $Details = $this->SHOPWARE_Article->getDetails();
     /**
      * @var Shopware\Models\Article\Detail $ItemVariation
      * @var Shopware\Models\Article\Configurator\Option $ConfiguratorOption
      */
     foreach ($Details as $ItemVariation) {
         $cacheAttributeValueSets[$ItemVariation->getId()] = array();
         $Object_AttributeVariantList = new PlentySoapObject_AttributeVariantList();
         foreach ($ItemVariation->getConfiguratorOptions() as $ConfiguratorOption) {
             $PLENTY_attributeValueID = PlentymarketsMappingController::getAttributeOptionByShopwareID($ConfiguratorOption->getId());
             $cacheAttributeValueSets[$ItemVariation->getId()][] = $PLENTY_attributeValueID;
             $Object_Integer = new PlentySoapObject_Integer();
             $Object_Integer->intValue = $PLENTY_attributeValueID;
             $Object_AttributeVariantList->AttributeValueIDs[] = $Object_Integer;
         }
         $objectsSetAttributeValueSets[] = $Object_AttributeVariantList;
     }
     foreach (array_chunk($objectsSetAttributeValueSets, 100) as $setAttributeValueSets) {
         // Complete the request
         $Request_SetItemAttributeVariants->SetAttributeValueSets = $setAttributeValueSets;
         // and go for it
         $Response_SetItemAttributeVariants = PlentymarketsSoapClient::getInstance()->SetItemAttributeVariants($Request_SetItemAttributeVariants);
         // Matching der Varianten
         foreach ($Response_SetItemAttributeVariants->ResponseMessages->item as $ResponseMessage) {
             if ($ResponseMessage->IdentificationKey != 'AttributeValueIDs') {
                 continue;
             }
             // If there is an error message, go ahead
             if (!is_null($ResponseMessage->ErrorMessages)) {
                 continue;
             }
             $PLENTY_attributeValueIDs = array_map('intval', explode(';', $ResponseMessage->IdentificationValue));
             $PLENTY_variantID = (int) $ResponseMessage->SuccessMessages->item[0]->Value;
             foreach ($cacheAttributeValueSets as $SHOPWARE_variantID => $attributeValueIDs) {
                 if (PlentymarketsUtils::arraysAreEqual($attributeValueIDs, $PLENTY_attributeValueIDs)) {
                     PlentymarketsMappingController::addItemVariant($SHOPWARE_variantID, sprintf('%s-%s-%s', $this->PLENTY_itemID, $this->PLENTY_priceID, $PLENTY_variantID));
                     break;
                 }
             }
         }
     }
     // Set the variation details ----------------------------------------------------------------------------------
     $objectsAttributeValueSetsDetails = array();
     // start the request
     $Request_SetAttributeValueSetsDetails = new PlentySoapRequest_SetAttributeValueSetsDetails();
     $Request_SetAttributeValueSetsDetails->AttributeValueSetsDetails = array();
     /** @var Shopware\Models\Article\Detail $ItemVariation */
     foreach ($Details as $ItemVariation) {
         try {
             $sku = PlentymarketsMappingController::getItemVariantByShopwareID($ItemVariation->getId());
         } catch (PlentymarketsMappingExceptionNotExistant $E) {
             // Roll back the item
             $this->rollback();
             // and quit
             throw new PlentymarketsExportException('The item variation with the number »' . $ItemVariation->getNumber() . '« could not be created (corrupt data)', 2880);
         }
         $Object_SetAttributeValueSetsDetails = new PlentySoapObject_SetAttributeValueSetsDetails();
         $Object_SetAttributeValueSetsDetails->Availability = $ItemVariation->getActive();
         // int
         $Object_SetAttributeValueSetsDetails->EAN1 = $ItemVariation->getEan();
         // string
         $Object_SetAttributeValueSetsDetails->MaxStock = null;
         // float
         $Object_SetAttributeValueSetsDetails->PurchasePrice = null;
         // float
         $Object_SetAttributeValueSetsDetails->SKU = $sku;
         $Object_SetAttributeValueSetsDetails->Variantnumber = $ItemVariation->getNumber();
         // string
         $objectsAttributeValueSetsDetails[] = $Object_SetAttributeValueSetsDetails;
     }
     foreach (array_chunk($objectsAttributeValueSetsDetails, 50) as $attributeValueSetsDetails) {
         $Request_SetAttributeValueSetsDetails->AttributeValueSetsDetails = $attributeValueSetsDetails;
         PlentymarketsSoapClient::getInstance()->SetAttributeValueSetsDetails($Request_SetAttributeValueSetsDetails);
     }
 }