package com.eactive.httpmockserver.server.service;

import com.eactive.httpmockserver.common.exception.NotFoundException;
import com.eactive.httpmockserver.server.entity.Server;
import com.eactive.httpmockserver.server.entity.ServerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
@Transactional
public class ServerMgmtService {

    @Autowired
    private ServerRepository serverRepository;

    public Page<Server> findAll(Specification<Server> serverSpecification, Pageable pageable) {
        return serverRepository.findAll(serverSpecification, pageable);
    }

    public Server findById(Long id) {
        return serverRepository.findById(id).orElseThrow(() -> new NotFoundException("Server Not Found"));
    }

    public void create(Server server) {
        serverRepository.save(server);
    }

    public void update(Long id, Server updated) {
        Server server = serverRepository.findById(id).orElseThrow(() -> new NotFoundException("Server Not Found"));

        server.setName(updated.getName());
        server.setScheme(updated.getScheme());
        server.setHostname(updated.getHostname());
        server.setBasePath(updated.getBasePath());
        server.setPort(updated.getPort());
        server.setEnabled(updated.isEnabled());

        serverRepository.save(server);


    }

    public void delete(Long id) {
        serverRepository.deleteById(id);
    }
}
