/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
*/

package org.apache.edgent.connectors.iotp.runtime;

import java.io.File;
import java.io.Serializable;
import java.util.Properties;

import org.apache.edgent.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;
import com.ibm.iotf.client.api.APIClient.ContentType;
import com.ibm.iotf.client.device.Command;
import com.ibm.iotf.client.device.DeviceClient;

/**
 * Device connector for IoTf.
 */
public class IotpConnector implements Serializable, AutoCloseable {
    private static final long serialVersionUID = 1L;
    private static final Logger logger = LoggerFactory.getLogger(IotpConnector.class);

    private Properties options;
    private File optionsFile;
    private transient DeviceClient client;
    private boolean disconnectOnClose = true;

    /**
     * Create a new connector to the specified MQTT server.
     *
     * @param options connector options
     */
    public IotpConnector(Properties options) {
        this.options = options;
    }

    public IotpConnector(File optionsFile) {
        this.optionsFile = optionsFile;
    }

    public IotpConnector(DeviceClient iotpDeviceClient) {
        this.client = iotpDeviceClient;
        this.disconnectOnClose = false;
    }

    synchronized DeviceClient connect() {
        DeviceClient client;
        try {
            client = getClient();
            if (!client.isConnected())
                client.connect();
            return client;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    synchronized DeviceClient getClient() throws Exception {
        if (client == null) {
            if (options == null)
                options = DeviceClient.parsePropertiesFile(optionsFile);

            client = new DeviceClient(options);
        }
        return client;
    }

    synchronized void subscribeCommands(Consumer<Command> tupleSubmitter) throws Exception {
        DeviceClient client = getClient();
        
        client.setCommandCallback(cmd -> {
            tupleSubmitter.accept(cmd);
        });
        
        connect();
    }

    void publishEvent(String eventId, JsonObject event, int qos) {
        DeviceClient client;
        try {
            client = connect();
        } catch (Exception e) {
            throw new RuntimeException(e);

        }
        client.publishEvent(eventId, event, qos);
    }

    void publishHttpEvent(String eventId, JsonObject event) {
        try {
            DeviceClient client = getClient();
            client.api().publishDeviceEventOverHTTP(eventId, event, ContentType.json);
        } catch (Exception e) {
            // throw new RuntimeException(e);
            // If the publish throws, a RuntimeException will cause
            // everything to unwind and the app/topology can terminate.
            // See the commentary/impl of MqttPublisher.accept().
            // See EDGENT-382
            logger.error("Unable to publish tuple for event " + eventId, e);
        }
    }

    @Override
    public void close() throws Exception {
        if (client == null)
            return;

        if (disconnectOnClose)
          client.disconnect();
        client = null;
    }
}

@@ -1024,16 +1024,58 @@
 Object;%0A
+import com.ibm.iotf.client.api.APIClient;%0A
 import c
@@ -3161,24 +3161,29 @@
   %7D%0A        
+if (!
 client.publi
@@ -3210,17 +3210,101 @@
 nt, qos)
-;
+) %7B%0A          logger.error(%22Publish event failed for eventId %7B%7D%22, eventId);%0A        %7D
 %0A    %7D%0A%0A
@@ -3391,35 +3391,29 @@
         
-Device
+API
 Client 
-client
+api
  = getCl
@@ -3410,32 +3410,38 @@
 pi = getClient()
+.api()
 ;%0A            cl
@@ -3442,20 +3442,16 @@
     
-client.
+if (!
 api
-()
 .pub
@@ -3507,17 +3507,114 @@
 pe.json)
-;
+) %7B%0A              logger.error(%22HTTP publish event failed for eventId %7B%7D%22, eventId);%0A            %7D
 %0A       
@@ -3964,21 +3964,21 @@
 publish 
-tuple
+event
  for eve
@@ -3983,12 +3983,15 @@
 vent
- %22 +
+Id %7B%7D%22,
  eve

add logging for some other publish failure conditions