/**
  * Singleton: returns an instance
  *
  * @return PlentymarketsImportItemStockStack
  */
 public static function getInstance()
 {
     if (!self::$Instance instanceof self) {
         self::$Instance = new self();
     }
     return self::$Instance;
 }
 /**
  * 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);
     }
 }
 /**
  * Finalizes the import
  */
 public function finish()
 {
     try {
         // Stock stack
         PlentymarketsImportItemStockStack::getInstance()->import();
     } catch (Exception $E) {
         PlentymarketsLogger::getInstance()->error('Sync:Item:Stock', 'PlentymarketsImportItemStockStack failed');
         PlentymarketsLogger::getInstance()->error('Sync:Item:Stock', $E->getMessage());
     }
     try {
         // Stock stack
         PlentymarketsImportControllerItemLinked::getInstance()->run();
     } catch (Exception $E) {
         PlentymarketsLogger::getInstance()->error('Sync:Item:Linked', 'PlentymarketsImportControllerItemLinked failed');
         PlentymarketsLogger::getInstance()->error('Sync:Item:Linked', $E->getMessage());
     }
     try {
         // Stock stack
         PlentymarketsImportItemImageThumbnailController::getInstance()->generate();
     } catch (Exception $E) {
         PlentymarketsLogger::getInstance()->error('Sync:Item:Image', 'PlentymarketsImportItemImageThumbnailController failed');
         PlentymarketsLogger::getInstance()->error('Sync:Item:Image', $E->getMessage());
     }
 }