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

import edu.prlab.tyler.iotgateway.cloud.pojo.device.Device;
import edu.prlab.tyler.iotgateway.cloud.pojo.privacy.PrivacyChoice;
import edu.prlab.tyler.iotgateway.cloud.pojo.privacy.PrivacyPolicyReport;
import edu.prlab.tyler.iotgateway.gateway.model.PrivacyChoiceResponse;
import edu.prlab.tyler.iotgateway.gateway.pojo.PrivacyChoiceIndex;
import edu.prlab.tyler.iotgateway.gateway.services.DeviceService;
import edu.prlab.tyler.iotgateway.gateway.services.PrivacyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
public class GatewayController {

    private DeviceService deviceService;
    private PrivacyService privacyService;


    @Autowired
    public GatewayController(PrivacyService privacyService,
                             DeviceService deviceService) {
        this.deviceService = deviceService;
        this.privacyService = privacyService;
    }

    // TODO
    //區塊鍊上綁定
    //回傳Device(暫時從DB撈)
    @PostMapping("/device/{udn}")
    public ResponseEntity<Device> bindDeviceAndGateway(@PathVariable(value = "udn") String udn) {
        return deviceService.bindDeviceAndGateway(udn)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.noContent().build());
    }

    // TODO
    //取得與該gateway所綁定的裝置列表
    //回傳Device列表(暫時從DB撈)
    @GetMapping("/device")
    public ResponseEntity<Iterable<Device>> readDevices() {
        return deviceService.readDevices()
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.noContent().build());
    }

    //透過裝置UDN取得裝置資訊與隱私政策
    @GetMapping("/privacy/{udn}")
    public ResponseEntity<PrivacyPolicyReport> readPrivacyPolicyReportByDevice(@PathVariable(value = "udn") String udn) {
        return privacyService.getRelatedPrivacyPolicies(udn)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.noContent().build());
    }

    //設定隱私選擇
    @PostMapping("/choice")
    public ResponseEntity<PrivacyChoiceResponse> setPrivacyChoice(@RequestBody PrivacyChoice privacyChoice) {
        return privacyService.setPrivacyPolicyChoice(privacyChoice)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.noContent().build());
    }

    // TODO
    //根據使用者取得在此gateway上該使用者的隱私選擇列表(根據時間排序)，
    //暫時從DB撈，無特定使用者
    @GetMapping("/choice")
    public ResponseEntity<Iterable<PrivacyChoiceResponse>> readPrivacyChoiceRecordsByUser() {
        return Optional.of(privacyService.getPrivacyPolicyChoices())
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.noContent().build());
    }
}
