package com.eshore.gringotts.web.domain.resource.service;

import com.eshore.gringotts.web.domain.base.repository.SimpleRepository;
import com.eshore.gringotts.web.domain.base.service.SimpleService;
import com.eshore.gringotts.web.domain.resource.entity.DataResource;
import com.eshore.gringotts.web.domain.resource.entity.format.ResourceFormat;
import com.eshore.gringotts.web.domain.resource.entity.type.ResourceType;
import com.eshore.gringotts.web.domain.resource.repository.DataResourceRepository;
import com.eshore.gringotts.web.domain.resource.repository.ResourceFormatRepository;
import com.eshore.gringotts.web.domain.resource.repository.ResourceTypeRepository;
import com.eshore.gringotts.web.domain.upload.entity.DataFile;
import com.eshore.gringotts.web.domain.user.entity.User;
import com.eshore.gringotts.web.domain.user.service.UserService;
import javax.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 数据资源服务
 *
 * @author lanyuanxiaoyao
 */
@Slf4j
@Service
public class DataResourceService extends SimpleService<DataResource, Long> {
    private final DataResourceRepository dataResourceRepository;
    private final ResourceTypeRepository resourceTypeRepository;
    private final ResourceFormatRepository resourceFormatRepository;
    private final UserService userService;

    public DataResourceService(DataResourceRepository dataResourceRepository, ResourceTypeRepository resourceTypeRepository, ResourceFormatRepository resourceFormatRepository, UserService userService) {
        this.dataResourceRepository = dataResourceRepository;
        this.resourceTypeRepository = resourceTypeRepository;
        this.resourceFormatRepository = resourceFormatRepository;
        this.userService = userService;
    }

    @Override
    protected SimpleRepository<DataResource, Long> repository() {
        return dataResourceRepository;
    }

    @Transactional
    public void create(String name, String description, ResourceFormat format, ResourceType type, DataFile example) {
        resourceFormatRepository.save(format);
        log.info("{}", type);
        resourceTypeRepository.save(type);
        DataResource resource = new DataResource();
        resource.setName(name);
        resource.setDescription(description);
        resource.setFormat(format);
        resource.setType(type);
        resource.setExample(example);
        User user = userService.currentLoginUser();
        resource.setCreatedUser(user);
        resource.setModifiedUser(user);
        dataResourceRepository.save(resource);
    }
}
