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

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 org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;

@Service
public class RemoteService {
    private RestTemplate template;
    private String cloudAddress;

    public RemoteService(RestTemplate template) {
        this.template = template;
    }

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

    public Optional<Device> readDevice(String udn) {
        try {
            return Optional.of(template.exchange(cloudAddress + "/device/" + udn, HttpMethod.GET, null, Device.class).getBody());
        } catch (Exception e) {
            System.out.println("Read device error");
            return Optional.empty();
        }
    }

    public Optional<Iterable<Device>> readDevices() {
        try {
            return Optional.of(template.exchange(cloudAddress + "/device", HttpMethod.GET, null,
                    new ParameterizedTypeReference<Iterable<Device>>() {
                    }).getBody());
        } catch (Exception e) {
            System.out.println("Read devices error");
            return Optional.empty();
        }
    }

    public Optional<PrivacyPolicyReport> readRelatedPrivacyPolicies(String udn) {
        try {
            return Optional.of(template.exchange(cloudAddress + "/privacy/" + udn, HttpMethod.GET, null,
                    PrivacyPolicyReport.class).getBody());
        } catch (Exception e) {
            System.out.println("Read privacyPolicyReport error");
            return Optional.empty();
        }
    }

    public Optional<PrivacyChoice> setPrivacyChoice(PrivacyChoice choice) {
        try {
            return Optional.of(template.exchange(cloudAddress + "/choice", HttpMethod.POST, new HttpEntity(choice), PrivacyChoice.class).getBody());
        } catch (Exception e) {
            System.out.println("Set privacyChoice error");
            return Optional.empty();
        }
    }

    public Optional<Iterable<PrivacyChoice>> readPrivacyChoices() {
        try {
            return Optional.of(template.exchange(cloudAddress + "/choice", HttpMethod.GET, null,
                    new ParameterizedTypeReference<Iterable<PrivacyChoice>>() {
                    }).getBody());
        } catch (Exception e) {
            System.out.println("Read privacyChoice error");
            return Optional.empty();
        }
    }
}
