package com.bytesw.bytebot.service;


import com.bytesw.bytebot.bean.ProxyBean;
import com.bytesw.bytebot.model.Proxy;
import com.bytesw.bytebot.repository.ProxyRepository;
import com.bytesw.xdf.exception.AlreadyExistsException;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

@Service
@Transactional
public class ProxyService extends XDFService<Proxy, ProxyBean, Long> {
    @Autowired
    private ProxyRepository proxyRepository;

    protected ProxyService(ProxyRepository repository) {
        super(repository);
    }


    @Override
    protected Proxy toModel(Proxy model, ProxyBean bean) {
        if (model == null) {
            model = new Proxy();
        }
        BeanUtils.copyProperties(bean, model);
        return model;
    }

    @Override
    protected ProxyBean toBean(Proxy model) {
        ProxyBean bean = new ProxyBean();
        BeanUtils.copyProperties(model, bean);
        return bean;
    }

    @Override
    public ProxyBean create(ProxyBean bean) {
        if (this.proxyRepository.existsById(bean.getId())) {
            throw new AlreadyExistsException();
        }
        Proxy model = new Proxy();
        model = this.proxyRepository.save(this.toModel(model, bean));
        return this.toBean(model);
    }

    @Override
    public ProxyBean update(ProxyBean bean, Long id) {
        Optional<Proxy> found = this.proxyRepository.findById(id);
        if (!found.isPresent()) {
            throw new NotFoundException();
        }
        Proxy model = this.toModel(found.get(), bean);
        BeanUtils.copyProperties(model, found.get());
        model = this.proxyRepository.save(found.get());
        return this.toBean(model);
    }

    @Override
    public void delete(Long id) {
        Optional<Proxy> found = this.proxyRepository.findById(id);
        if (!found.isPresent()) {
            throw new NotFoundException();
        }
        this.proxyRepository.delete(found.get());
    }
}
