package de.htwsaar.webshop.service.impl;

import de.htwsaar.webshop.model.FarmImageModel;
import de.htwsaar.webshop.repository.FarmImageRepository;
import de.htwsaar.webshop.repository.entities.Article;
import de.htwsaar.webshop.repository.entities.FarmImage;
import de.htwsaar.webshop.service.ArticleService;
import de.htwsaar.webshop.service.FarmImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class FarmImageServiceImpl implements FarmImageService {
    private final FarmImageRepository farmImageRepository;
    private final ArticleService articleService;

    @Autowired
    public FarmImageServiceImpl(FarmImageRepository imageRepository, ArticleService articleService) {
        this.farmImageRepository = imageRepository;
        this.articleService = articleService;
    }

    @Override
    public FarmImage getStandardImage() {
        return farmImageRepository.findFarmImageByStandard(true);
    }

    @Override
    public FarmImage getImageByUUID(UUID uuid) {
        return farmImageRepository.findFarmImageByArticle_Uuid(uuid);
    }

    @Override
    public FarmImage getImageById(Long imageId) {
        return farmImageRepository.findFarmImageById(imageId);
    }

    @Override
    @Transactional
    public FarmImage save(FarmImage image) {
        return farmImageRepository.save(image);
    }

    @Override
    public FarmImage save(FarmImageModel model) {
        return save(new FarmImage(model.getId(), articleService.findByUUID(model.getArticleUuid()), model.getBase64(), model.getStandard()));
    }

    @Override
    public FarmImage save(UUID uuid, String base64, boolean standard) {
        if (uuid == null) {
            log.warn("Got no UUID, aborting");
            return null;
        }
        Article article = articleService.findByUUID(uuid);
        if (article == null) {
            log.warn("Could not find article with id {}", uuid);
            return null;
        }
        if (base64 == null || base64.isEmpty()) {
            log.warn("Got no file for {}", uuid);
            return null;
        }

        return farmImageRepository.save(new FarmImage(null, article, base64, standard));
    }

    @Override
    @Transactional
    public void deleteById(Long imageId) {
        farmImageRepository.deleteById(imageId);
    }
}
