package edu.prlab.tyler.iotgateway.cloud.controllers;

import edu.prlab.tyler.iotgateway.cloud.pojo.device.Device;
import edu.prlab.tyler.iotgateway.cloud.pojo.privacy.PrivacyPolicyReport;
import edu.prlab.tyler.iotgateway.cloud.services.DeviceService;
import edu.prlab.tyler.iotgateway.cloud.services.PrivacyPolicyReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;

@RestController
@RequestMapping
public class DeviceController {
    private DeviceService deviceService;
    private PrivacyPolicyReportService privacyPolicyReportService;
    @Autowired
    public DeviceController(DeviceService deviceService,
                            PrivacyPolicyReportService privacyPolicyReportService
                            ) {
        this.deviceService = deviceService;
        this.privacyPolicyReportService = privacyPolicyReportService;
    }

    @PostMapping("/device")
    public ResponseEntity<Device> addDevice(@RequestBody Device device) {
        return deviceService.add(device)
                .map(ResponseEntity::ok)
                .orElseGet(()->ResponseEntity.noContent().build());
    }

    @GetMapping("/device/{udn}")
    public ResponseEntity<Device> readDevice(@PathVariable(value = "udn",required = false) String udn) {
        return deviceService.readByUDN(udn)
                .map(ResponseEntity::ok)
                .orElseGet(()->ResponseEntity.noContent().build());
    }

    @GetMapping("/device")
    public ResponseEntity<Iterable<Device>> readDevices() {
        return Optional.of(deviceService.readll())
                .map(ResponseEntity::ok)
                .orElseGet(()->ResponseEntity.noContent().build());
    }

    @PostMapping("/privacy")
    public  ResponseEntity<PrivacyPolicyReport> addPrivacyPolicyReport(@RequestBody PrivacyPolicyReport privacyPolicy) {
        return  privacyPolicyReportService.add(privacyPolicy)
                    .map(ResponseEntity::ok)
                    .orElseGet(()->ResponseEntity.noContent().build());
    }

    @GetMapping("/privacy/{UDN}")
    public ResponseEntity<PrivacyPolicyReport> readPrivacyPolicyReportByDevice(@PathVariable(value = "UDN") String UDN) {
        return privacyPolicyReportService.readByDevice(UDN)
                .map(ResponseEntity::ok)
                .orElseGet(()->ResponseEntity.noContent().build());
    }
}
