/**
  * @param PlentySoapResponse_ObjectItemImage $Image
  * @param Media $mediaResource
  *
  * @return MediaModel
  *
  * @throws NotFoundException
  * @throws PlentymarketsMappingExceptionNotExistant
  */
 protected function updateMedia(PlentySoapResponse_ObjectItemImage $Image, Media $mediaResource)
 {
     $mediaId = PlentymarketsMappingController::getMediaByPlentyID($Image->ImageID);
     if (empty($mediaId)) {
         throw new PlentymarketsMappingExceptionNotExistant();
     }
     /**
      * @var MediaModel $media
      */
     $media = Shopware()->Models()->getRepository('Shopware\\Models\\Media\\Media')->find($mediaId);
     if (empty($media)) {
         throw new NotFoundException();
     }
     $attributes = $media->getAttribute();
     if (empty($attributes)) {
         $attributes = new MediaAttributes();
         $media->setAttribute($attributes);
         Shopware()->Models()->persist($attributes);
     }
     $hash = $attributes->getPlentyHash();
     if (empty($hash)) {
         $hash = $attributes->setPlentyHash(sha1_file($media->getPath()));
         Shopware()->Models()->persist($attributes);
     }
     $newHash = sha1_file($Image->ImageURL);
     if ($hash != $newHash) {
         // remove old media
         Shopware()->Models()->remove($media);
         $newMedia = $this->createMedia($Image, $mediaResource);
         // update old article images
         $images = $media->getArticles();
         /**
          * @var Shopware\Models\Article\Image $image
          */
         foreach ($images as $image) {
             $image->setMedia($newMedia);
             $image->setPath($newMedia->getName());
             $image->setExtension($newMedia->getExtension());
             $image->setDescription($newMedia->getDescription());
             Shopware()->Models()->persist($image);
         }
         $media = $newMedia;
     }
     Shopware()->Models()->flush();
     return $media;
 }