package com.thesis.centralserver.controllers;

import com.thesis.centralserver.dtos.DeviceDTO;
import com.thesis.centralserver.dtos.OffloadingTaskDTO;
import com.thesis.centralserver.entities.DeviceMode;
import com.thesis.centralserver.entities.mappers.DeviceMapper;
import com.thesis.centralserver.entities.mappers.OffloadingTaskMapper;
import com.thesis.centralserver.exceptions.NoSellerDeviceFoundException;
import com.thesis.centralserver.services.DeviceService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/devices")
public class DeviceController {

    private final DeviceService deviceService;

    public DeviceController(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @PostMapping("/update")
    public DeviceDTO update(HttpServletRequest request,
                            @Valid @RequestBody DeviceDTO deviceDTO) {

        deviceDTO.setIp(request.getRemoteAddr());

        return DeviceMapper.createDeviceDTO(deviceService.updateDeviceData(deviceDTO));

    }

    @GetMapping("/")
    public List<DeviceDTO> getAllDevices() {
        return DeviceMapper.createDeviceDTOList(deviceService.getAllDevices());
    }

    @PostMapping("/seller_devices")
    public OffloadingTaskDTO getSellerDevices(HttpServletRequest request,
                                              @Valid @RequestParam double dataSize,
                                              @Valid @RequestBody DeviceDTO deviceDTO)
            throws NoSellerDeviceFoundException {

        deviceDTO.setIp(request.getRemoteAddr());
        deviceDTO.setDeviceMode(DeviceMode.BUYER);

        return OffloadingTaskMapper.createTaskDTO(deviceService.getSellerDevices(dataSize, deviceDTO));

    }

}
