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

import edu.prlab.tyler.iotgateway.cloud.pojo.device.Device;
import edu.prlab.tyler.iotgateway.gateway.pojo.DeviceIndex;
import edu.prlab.tyler.iotgateway.gateway.repositories.DeviceIndexRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;

@Service
public class DeviceService {
    private RestTemplate template;

    DeviceIndexRepository deviceIndexRepository;
    private String cloudAddress;

    @Autowired
    public DeviceService(DeviceIndexRepository deviceIndexRepository,
                         RestTemplate template) {
        this.deviceIndexRepository = deviceIndexRepository;
        this.template = template;
    }

    @Value("${iotgateway.cloud.address}")
    private void setCloudAddress(String cloudAddress) {
        this.cloudAddress = cloudAddress;
    }

    //TODO bind and read from blockchain
    public Optional<Device> bindDeviceAndGateway(String udn) {
        return Optional.ofNullable(template.getForObject(cloudAddress + "/device/" + udn, Device.class));
//                .map(device -> deviceIndexRepository.save(DeviceIndex.builder().udn(udn).build()));
    }

    public Optional<Iterable<Device>> readDevices() {
        return Optional.ofNullable(template.exchange(cloudAddress + "/device", HttpMethod.GET,null,
                new ParameterizedTypeReference<Iterable<Device>>() { }).getBody());
    }

}