/**
  * Constructor method
  *
  * @param PlentySoapObject_ItemBase $ItemBase
  */
 public function __construct($ItemBase)
 {
     $this->ItemBase = $ItemBase;
     foreach ($this->ItemBase->ItemAttributeMarkup->item as $ItemAttributeMarkup) {
         // May be percentage or flat rate surcharge
         $this->valueId2markup[$ItemAttributeMarkup->ValueID] = (double) $ItemAttributeMarkup->Markup;
     }
     //
     $Request_GetAttributeValueSets = new PlentySoapRequest_GetAttributeValueSets();
     $valueIds = array();
     $chunks = array_chunk($this->ItemBase->AttributeValueSets->item, 50);
     foreach ($chunks as $chunk) {
         $Request_GetAttributeValueSets->AttributeValueSets = array();
         // Attribute Value Sets abfragen
         foreach ($chunk as $AttributeValueSet) {
             //
             $this->variants[$AttributeValueSet->AttributeValueSetID] = array();
             //
             $RequestObject_GetAttributeValueSets = new PlentySoapRequestObject_GetAttributeValueSets();
             $RequestObject_GetAttributeValueSets->AttributeValueSetID = $AttributeValueSet->AttributeValueSetID;
             $RequestObject_GetAttributeValueSets->Lang = 'de';
             $Request_GetAttributeValueSets->AttributeValueSets[] = $RequestObject_GetAttributeValueSets;
         }
         $Response_GetAttributeValueSets = PlentymarketsSoapClient::getInstance()->GetAttributeValueSets($Request_GetAttributeValueSets);
         /**
          * @var PlentySoapObject_AttributeValueSet $AttributeValueSet
          * @var PlentySoapObject_Attribute $Attribute
          */
         foreach ($Response_GetAttributeValueSets->AttributeValueSets->item as $AttributeValueSet) {
             $this->variant2markup[$AttributeValueSet->AttributeValueSetID] = 0;
             foreach ($AttributeValueSet->Attribute->item as $Attribute) {
                 //
                 if (!array_key_exists($Attribute->AttributeFrontendName, $this->groups)) {
                     try {
                         $attributeId = PlentymarketsMappingController::getAttributeGroupByPlentyID($Attribute->AttributeID);
                         $group = array('id' => $attributeId, 'options' => array());
                     } catch (Exception $e) {
                         $group = array('name' => $Attribute->AttributeFrontendName, 'options' => array());
                     }
                     $this->groups[$Attribute->AttributeFrontendName] = $group;
                     $this->groupId2optionName2plentyId[$Attribute->AttributeID] = array();
                     $this->groupName2plentyId[$Attribute->AttributeFrontendName] = $Attribute->AttributeID;
                 }
                 //
                 $this->configuratorOptions[$AttributeValueSet->AttributeValueSetID][] = array('group' => $Attribute->AttributeFrontendName, 'option' => $Attribute->AttributeValue->ValueFrontendName);
                 //
                 if (!in_array($Attribute->AttributeValue->ValueID, $valueIds)) {
                     try {
                         $valueId = PlentymarketsMappingController::getAttributeOptionByPlentyID($Attribute->AttributeValue->ValueID);
                         $option = array('id' => $valueId);
                     } catch (Exception $e) {
                         $option = array('name' => $Attribute->AttributeValue->ValueFrontendName);
                     }
                     $this->groups[$Attribute->AttributeFrontendName]['options'][] = $option;
                     $this->groupId2optionName2plentyId[$Attribute->AttributeID][$Attribute->AttributeValue->ValueFrontendName] = $Attribute->AttributeValue->ValueID;
                     $valueIds[] = $Attribute->AttributeValue->ValueID;
                 }
                 if ($this->valueId2markup[$Attribute->AttributeValue->ValueID]) {
                     $markup = $this->valueId2markup[$Attribute->AttributeValue->ValueID];
                 } else {
                     $markup = (double) $Attribute->AttributeValue->Markup;
                 }
                 if ($markup) {
                     if ($Attribute->MarkupPercental == 1) {
                         $markup = $this->ItemBase->PriceSet->Price / 100 * $markup;
                     }
                     $this->variant2markup[$AttributeValueSet->AttributeValueSetID] += $markup;
                 }
             }
         }
     }
 }
    /**
     * Retrieves the images from plentymarkets and adds them to the item.
     *
     * @return number
     */
    public function image()
    {
        $plentyId2ShopwareId = array();
        $shopwareId2PlentyPosition = array();
        $Request_GetItemsImages = new PlentySoapRequest_GetItemsImages();
        $Request_GetItemsImages->Page = 0;
        $Request_GetItemsImages->SKU = $this->PLENTY_itemId;
        // Cleanup
        $this->purge();
        /**
         * @var Media $mediaResource
         */
        $mediaResource = \Shopware\Components\Api\Manager::getResource('Media');
        do {
            /**
             * @var PlentySoapResponse_GetItemsImages $Response_GetItemsImages
             */
            $Response_GetItemsImages = PlentymarketsSoapClient::getInstance()->GetItemsImages($Request_GetItemsImages);
            if ($Response_GetItemsImages->Success == false) {
                PlentymarketsLogger::getInstance()->error('Sync:Item:Image', 'The images for the plentymarkets item id »' . $this->PLENTY_itemId . '« could not be retrieved', 3200);
                continue;
            }
            /**
             * @var $Image PlentySoapResponse_ObjectItemImage
             */
            foreach ($Response_GetItemsImages->ItemsImages->item as $Image) {
                $shopwareStoreIds = array();
                /**
                 * @var $reference PlentySoapResponse_ObjectGetItemImageReference
                 */
                foreach ($Image->References->item as $reference) {
                    if ($reference->ReferenceType == 'Mandant') {
                        try {
                            if (PlentymarketsMappingController::getShopByPlentyID($reference->ReferenceValue) > 0) {
                                $shopwareStoreId = PlentymarketsMappingController::getShopByPlentyID($reference->ReferenceValue);
                            }
                        } catch (PlentymarketsMappingExceptionNotExistant $E) {
                            continue;
                        }
                        if (isset($shopwareStoreId)) {
                            $shopwareStoreIds[] = $shopwareStoreId;
                        }
                    }
                }
                // Skip the image if it should not be shown
                if (empty($shopwareStoreIds)) {
                    continue;
                } else {
                    try {
                        $media = $this->updateMedia($Image, $mediaResource);
                    } catch (PlentymarketsMappingExceptionNotExistant $e) {
                        $media = $this->createMedia($Image, $mediaResource);
                    } catch (NotFoundException $e) {
                        $media = $this->createMedia($Image, $mediaResource);
                    } catch (Exception $e) {
                        PlentymarketsLogger::getInstance()->error('Sync:Item:Image', $e->getMessage(), 3200);
                        continue;
                    }
                    $image = new Image();
                    $image->setMain(2);
                    $image->setMedia($media);
                    $image->setPath($media->getName());
                    $image->setExtension($media->getExtension());
                    // get the main language of the shop
                    //$mainLangData = array_values(PlentymarketsTranslation::getInstance()->getShopMainLanguage($shopwareStoreId));
                    //$mainLang = PlentymarketsTranslation::getInstance()->getPlentyLocaleFormat($mainLangData[0]['locale']);
                    foreach ($Image->Names->item as $imageName) {
                        if ($imageName->Lang == 'de') {
                            // set the image title in German
                            $image->setDescription($imageName->Name);
                        }
                    }
                    if (!is_null(PlentymarketsConfig::getInstance()->getItemImageAltAttributeID()) && PlentymarketsConfig::getInstance()->getItemImageAltAttributeID() > 0 && PlentymarketsConfig::getInstance()->getItemImageAltAttributeID() <= 3) {
                        // get the attribute number for alternative text from connector's settings
                        $plenty_attributeID = PlentymarketsConfig::getInstance()->getItemImageAltAttributeID();
                        // set the value for the attribute number
                        $attribute = new \Shopware\Models\Attribute\ArticleImage();
                        call_user_func(array($attribute, 'setAttribute' . $plenty_attributeID), $Image->Names->item[0]->AlternativeText);
                        $image->setAttribute($attribute);
                    }
                    $image->setPosition($Image->Position);
                    // Generate the thumbnails
                    if (version_compare(Shopware::VERSION, '4.2') != 1) {
                        PlentymarketsImportItemImageThumbnailController::getInstance()->addMediaResource($media);
                    }
                    Shopware()->Models()->persist($image);
                    Shopware()->Models()->flush();
                    $imageId = $image->getId();
                    foreach ($shopwareStoreIds as $shopwareStoreId) {
                        // import the image title translations for all active shops of the image
                        $this->importImageTitleTranslation($imageId, $Image->Names->item, $shopwareStoreId);
                    }
                    $plentyId2ShopwareId[$Image->ImageID] = $imageId;
                    $shopwareId2PlentyPosition[$Image->Position] = $imageId;
                    Shopware()->DB()->query('
											UPDATE s_articles_img
												SET articleID = ?
												WHERE id = ?
										', array($this->SHOPWARE_itemId, $imageId));
                }
            }
        } while (++$Request_GetItemsImages->Page < $Response_GetItemsImages->Pages);
        if (empty($shopwareId2PlentyPosition)) {
            return;
        }
        ksort($shopwareId2PlentyPosition);
        $mainImageId = reset($shopwareId2PlentyPosition);
        if (empty($mainImageId)) {
            return;
        }
        /**
         * @var Shopware\Models\Article\Image $mainImage
         */
        $mainImage = Shopware()->Models()->find('Shopware\\Models\\Article\\Image', $mainImageId);
        $mainImage->setMain(1);
        Shopware()->Models()->persist($mainImage);
        Shopware()->Models()->flush();
        // Get the variant images
        $Request_GetItemsVariantImages = new PlentySoapRequest_GetItemsVariantImages();
        $Request_GetItemsVariantImages->Items = array();
        $RequestObject_GetItemsVariantImages = new PlentySoapRequestObject_GetItemsVariantImages();
        $RequestObject_GetItemsVariantImages->ItemID = $this->PLENTY_itemId;
        $Request_GetItemsVariantImages->Items[] = $RequestObject_GetItemsVariantImages;
        /**
         * @var PlentySoapResponse_GetItemsVariantImages $Response_GetItemsVariantImages
         */
        $Response_GetItemsVariantImages = PlentymarketsSoapClient::getInstance()->GetItemsVariantImages($Request_GetItemsVariantImages);
        foreach ($Response_GetItemsVariantImages->Images->item as $GetItemsVariantImagesImage) {
            try {
                $shopwareOptionId = PlentymarketsMappingController::getAttributeOptionByPlentyID($GetItemsVariantImagesImage->AttributeValueID);
                /**
                 * @var \Shopware\Models\Article\Configurator\Option $shopwareOption
                 */
                $shopwareOption = Shopware()->Models()->find('Shopware\\Models\\Article\\Configurator\\Option', $shopwareOptionId);
            } catch (PlentymarketsMappingExceptionNotExistant $e) {
                continue;
            }
            if (!isset($plentyId2ShopwareId[$GetItemsVariantImagesImage->ImageID])) {
                continue;
            }
            /** @var Shopware\Models\Article\Image $shopwareImage */
            $shopwareImageId = $plentyId2ShopwareId[$GetItemsVariantImagesImage->ImageID];
            /**
             * @var Image $shopwareImage
             */
            $shopwareImage = Shopware()->Models()->find('Shopware\\Models\\Article\\Image', $shopwareImageId);
            $mapping = new Shopware\Models\Article\Image\Mapping();
            $mapping->setImage($shopwareImage);
            $rule = new Shopware\Models\Article\Image\Rule();
            $rule->setMapping($mapping);
            $rule->setOption($shopwareOption);
            $mapping->getRules()->add($rule);
            $shopwareImage->setMappings($mapping);
            Shopware()->Models()->persist($mapping);
            $details = Shopware()->Db()->fetchCol('
				SELECT
						d.id
					FROM s_articles_details d
						INNER JOIN s_article_configurator_option_relations alias16 ON alias16.option_id = ' . $shopwareOptionId . ' AND alias16.article_id = d.id
					WHERE d.articleID = ' . $this->SHOPWARE_itemId . '
			');
            foreach ($details as $detailId) {
                /**
                 * Get the detail object
                 *
                 * @var Shopware\Models\Article\Detail $detail
                 */
                $detail = Shopware()->Models()->getReference('Shopware\\Models\\Article\\Detail', $detailId);
                // Create the variant image
                $variantImage = new Shopware\Models\Article\Image();
                $variantImage->setExtension($shopwareImage->getExtension());
                $variantImage->setMain($shopwareImage->getMain());
                $variantImage->setParent($shopwareImage);
                $variantImage->setArticleDetail($detail);
                // And persist it
                Shopware()->Models()->persist($variantImage);
            }
        }
        Shopware()->Db()->update('s_articles', array('changetime' => date('c', time())), 'id=' . $this->SHOPWARE_itemId);
        Shopware()->Models()->flush();
    }
 /**
  * Imports the values
  */
 protected function importValues()
 {
     if (!$this->Group) {
         return;
     }
     /**
      * @var PlentySoapObject_GetItemAttributesAttributeValue $Value
      * @var Shopware\Models\Article\Configurator\Option $Option
      */
     foreach ($this->Attribute->Values->item as $Value) {
         try {
             $SHOPWARE_optionId = PlentymarketsMappingController::getAttributeOptionByPlentyID($Value->ValueId);
         } catch (PlentymarketsMappingExceptionNotExistant $E) {
             continue;
         }
         foreach ($this->Group->getOptions() as $Option) {
             if ($Option->getId() != $SHOPWARE_optionId) {
                 continue;
             }
             if (!is_null($Value->FrontendName)) {
                 $Option->setName($Value->FrontendName);
             } elseif (!is_null($Value->BackendName)) {
                 // use backend-name if frontend-name doesn't exists
                 $Option->setName($Value->BackendName);
             } else {
                 continue;
             }
             $Option->setPosition($Value->Position);
         }
     }
 }