package com.eactive.httpmockserver.server.mapper;


import com.eactive.httpmockserver.common.exception.NotFoundException;
import com.eactive.httpmockserver.server.dto.ServerDTO;
import com.eactive.httpmockserver.server.entity.Server;
import com.eactive.httpmockserver.server.entity.ServerRepository;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Mapper(componentModel = "spring",
        unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Component
public class ServerMapper {

    @Autowired
    ServerRepository serverRepository;

    public Server mapById(Long id) {
        if (id == null || id == 0) return null;
        return serverRepository.findById(id).orElseThrow(() -> new NotFoundException("Server[" + id + "] not found"));
    }

    public Long mapById(Server server) {
        if (server == null) return null;
        return server.getId();
    }

    public ServerDTO map(Server server) {
        if (server == null) return null;
        ServerDTO dto = new ServerDTO();

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

        return dto;
    }


    public Server map(ServerDTO dto) {
        if (dto == null) return null;

        Server server = new Server();

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

        return server;
    }
}
