/**
 * Copyright (c) 2010-2020 Contributors to the openHAB project
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 */

 /* ***********************************************************
 * This file was automatically generated on 2022-01-03.      *
 *                                                           *
 * openHAB Bindings Version 2.0.0                            *
 *                                                           *
 * If you have a bugfix for this file and want to commit it, *
 * please fix the bug in the generator. You can find a link  *
 * to the generators git repository on tinkerforge.com       *
 *************************************************************/

package org.openhab.binding.tinkerforge.internal.device;

import java.net.URI;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.config.core.ConfigDescription;
import org.eclipse.smarthome.config.core.ConfigDescriptionBuilder;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameter.Type;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameterBuilder;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameterGroup;
import org.eclipse.smarthome.config.core.ParameterOption;
import org.eclipse.smarthome.core.types.State;
import org.eclipse.smarthome.core.types.StateOption;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.CommandDescriptionBuilder;
import org.eclipse.smarthome.core.types.CommandOption;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.binding.BaseThingHandler;
import org.eclipse.smarthome.core.thing.type.ChannelDefinitionBuilder;
import org.eclipse.smarthome.core.thing.type.ChannelType;
import org.eclipse.smarthome.core.thing.type.ChannelTypeBuilder;
import org.eclipse.smarthome.core.thing.type.ChannelTypeUID;
import org.eclipse.smarthome.core.types.RefreshType;
import org.eclipse.smarthome.core.thing.type.ThingType;
import org.eclipse.smarthome.core.thing.type.ThingTypeBuilder;
import org.eclipse.smarthome.core.types.StateDescriptionFragmentBuilder;
import org.openhab.binding.tinkerforge.internal.TinkerforgeBindingConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.eclipse.smarthome.core.library.types.DecimalType;
import org.eclipse.smarthome.core.library.types.QuantityType;
import org.eclipse.smarthome.core.library.unit.MetricPrefix;
import org.eclipse.smarthome.core.library.unit.SIUnits;
import org.eclipse.smarthome.core.library.unit.SmartHomeUnits;
import org.eclipse.smarthome.core.thing.CommonTriggerEvents;

import com.tinkerforge.BrickletRS232V2;
import com.tinkerforge.IPConnection;
import com.tinkerforge.TinkerforgeException;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;

/**
 * Wraps the Java Bindings of the RS232 Bricklet 2.0.
 * @author Erik Fleckstein - Initial contribution
 */
@NonNullByDefault
public class BrickletRS232V2Wrapper extends BrickletRS232V2 implements CoMCUFlashable, DeviceWrapper {
    public static final DeviceInfo DEVICE_INFO = new DeviceInfo(BrickletRS232V2.DEVICE_DISPLAY_NAME, "brickletrs232v2", BrickletRS232V2.DEVICE_IDENTIFIER, BrickletRS232V2Wrapper.class, BrickletRS232V2Actions.class, "2.0.3", true);

    public BrickletRS232V2Wrapper(String uid, IPConnection ipcon) {
        super(uid, ipcon);
    }

    private List<ScheduledFuture<?>> manualChannelUpdates = new ArrayList<>();
    private List<ListenerReg<?>> listenerRegs = new ArrayList<>();

    public void cancelManualUpdates() {
        manualChannelUpdates.forEach(f -> f.cancel(true));
    }

    public <T> T reg(T listener, Consumer<T> toRemove) {
        listenerRegs.add(new ListenerReg<T>(listener, toRemove));
        return listener;
    }

    
    private final Logger logger = LoggerFactory.getLogger(BrickletRS232V2Wrapper.class);

    @Override
    public void initialize(org.eclipse.smarthome.config.core.Configuration config, Function<String, org.eclipse.smarthome.config.core.Configuration> getChannelConfigFn, BiConsumer<String, org.eclipse.smarthome.core.types.State> updateStateFn, BiConsumer<String, String> triggerChannelFn, ScheduledExecutorService scheduler, BaseThingHandler handler) throws TinkerforgeException {
        this.setResponseExpectedAll(true);
        BrickletRS232V2Config cfg = (BrickletRS232V2Config) config.as(BrickletRS232V2Config.class);
        this.addFrameReadableListener(this.reg((frameCount) -> {if(true) {triggerChannelFn.accept("BrickletRS232V2FrameReadable", transformBrickletRS232V2FrameReadableCallback0(frameCount, cfg));}}, this::removeFrameReadableListener));
		this.addErrorCountListener(this.reg((errorCountOverrun, errorCountParity) -> {if(true) {updateStateFn.accept("BrickletRS232V2OverrunErrorCount", transformBrickletRS232V2OverrunErrorCountCallback0(errorCountOverrun, errorCountParity, cfg));}}, this::removeErrorCountListener));
		this.addErrorCountListener(this.reg((errorCountOverrun, errorCountParity) -> {if(true) {updateStateFn.accept("BrickletRS232V2ParityErrorCount", transformBrickletRS232V2ParityErrorCountCallback0(errorCountOverrun, errorCountParity, cfg));}}, this::removeErrorCountListener));
        this.setConfiguration(cfg.baudRate, cfg.parity, cfg.stopBits, cfg.wordLength, cfg.flowControl);
		    this.setBufferConfig(cfg.sendBufferSize, 10240 - cfg.sendBufferSize);
		    this.setFrameReadableCallbackConfiguration(cfg.frameSize);
		this.setStatusLEDConfig(cfg.statusLEDConfig);
		{
		BrickletRS232V2SendBufferUsedConfig channelCfg = getChannelConfigFn.apply("BrickletRS232V2SendBufferUsed").as(BrickletRS232V2SendBufferUsedConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickletRS232V2SendBufferUsed"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
		{
		BrickletRS232V2ReceiveBufferUsedConfig channelCfg = getChannelConfigFn.apply("BrickletRS232V2ReceiveBufferUsed").as(BrickletRS232V2ReceiveBufferUsedConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickletRS232V2ReceiveBufferUsed"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
    }

    @Override
    public void dispose(org.eclipse.smarthome.config.core.Configuration config) throws TinkerforgeException {
        listenerRegs.forEach(ListenerReg::deregister);

        
        
    }

    @Override
    public List<String> getEnabledChannels(org.eclipse.smarthome.config.core.Configuration config) throws TinkerforgeException{
        List<String> result = new ArrayList<String>();
        result.add("BrickletRS232V2FrameReadable");
		result.add("BrickletRS232V2OverrunErrorCount");
		result.add("BrickletRS232V2ParityErrorCount");
		result.add("BrickletRS232V2SendBufferUsed");
		result.add("BrickletRS232V2ReceiveBufferUsed");
        return result;
    }

    public static @Nullable ChannelType getChannelType(ChannelTypeUID channelTypeUID) {
        switch(channelTypeUID.getId()) {
            case "BrickletRS232V2OverrunErrorCount":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletRS232V2OverrunErrorCount"), "Overrun Error Count", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletRS232V2OverrunErrorCount")).withDescription("The current number of overrun errors")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%d").withReadOnly(true).build().toStateDescription()).build();
            case "BrickletRS232V2ParityErrorCount":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletRS232V2ParityErrorCount"), "Framing Error Count", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletRS232V2ParityErrorCount")).withDescription("The current number of parity errors")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%d").withReadOnly(true).build().toStateDescription()).build();
            case "BrickletRS232V2SendBufferUsed":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletRS232V2SendBufferUsed"), "Send Buffer Used", "Number:DataAmount").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletRS232V2SendBufferUsed")).withDescription("The number of bytes currently in the send buffer")
.withStateDescription(StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(9216)).withStep(BigDecimal.valueOf(1)).withPattern("%d %unit%").withReadOnly(true).build().toStateDescription()).build();
            case "BrickletRS232V2ReceiveBufferUsed":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletRS232V2ReceiveBufferUsed"), "Receive Buffer Used", "Number:DataAmount").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletRS232V2ReceiveBufferUsed")).withDescription("The number of bytes currently in the receive buffer")
.withStateDescription(StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(9216)).withStep(BigDecimal.valueOf(1)).withPattern("%d %unit%").withReadOnly(true).build().toStateDescription()).build();
default:
                break;
        }

        return null;
    }

    public static ThingType getThingType(ThingTypeUID thingTypeUID) {
             Map<String, String> thingTypeProperties = ThingTypeBuilder.instance(thingTypeUID, "unused").build().getProperties();
             Map<String, String> props = new HashMap<String, String>(thingTypeProperties);
             props.putIfAbsent(TinkerforgeBindingConstants.PROPERTY_MINIMUM_FIRMWARE_VERSION, DEVICE_INFO.minimumFWVersion);
        return ThingTypeBuilder.instance(thingTypeUID, "Tinkerforge RS232 Bricklet 2.0").isListed(false).withSupportedBridgeTypeUIDs(Arrays.asList(TinkerforgeBindingConstants.THING_TYPE_BRICK_DAEMON.toString())).withConfigDescriptionURI(URI.create("thing-type:tinkerforge:" + thingTypeUID.getId())).withDescription("Communicates with RS232 devices").withChannelDefinitions(Arrays.asList(new ChannelDefinitionBuilder("BrickletRS232V2FrameReadable", new ChannelTypeUID("system", "trigger")).withLabel("Frame Readable").withDescription("This channel is triggered in when a new frame was received and can be read out. The channel will only trigger again if the frame was read.").build(), new ChannelDefinitionBuilder("BrickletRS232V2OverrunErrorCount", new ChannelTypeUID("tinkerforge", "BrickletRS232V2OverrunErrorCount")).withLabel("Overrun Error Count").build(), new ChannelDefinitionBuilder("BrickletRS232V2ParityErrorCount", new ChannelTypeUID("tinkerforge", "BrickletRS232V2ParityErrorCount")).withLabel("Parity Error Count").build(), new ChannelDefinitionBuilder("BrickletRS232V2SendBufferUsed", new ChannelTypeUID("tinkerforge", "BrickletRS232V2SendBufferUsed")).withLabel("Send Buffer Used").build(), new ChannelDefinitionBuilder("BrickletRS232V2ReceiveBufferUsed", new ChannelTypeUID("tinkerforge", "BrickletRS232V2ReceiveBufferUsed")).withLabel("Receive Buffer Used").build())).withProperties(props).build();
    }

    public static @Nullable ConfigDescription getConfigDescription(URI uri) {
        switch(uri.toASCIIString()) {
            case "thing-type:tinkerforge:brickletrs232v2":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList(ConfigDescriptionParameterBuilder.create("baudRate", Type.INTEGER).withDefault("115200").withDescription("The baud rate to send/receive with.").withLabel("Baud Rate").withMinimum(BigDecimal.valueOf(100)).withMaximum(BigDecimal.valueOf(2000000)).build(), ConfigDescriptionParameterBuilder.create("parity", Type.INTEGER).withDefault("0").withDescription("The parity mode to use. See here: https://en.wikipedia.org/wiki/Serial_port#Parity.").withLabel("Parity").withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("0", "None"), new ParameterOption("1", "Odd"), new ParameterOption("2", "Even"))).build(), ConfigDescriptionParameterBuilder.create("stopBits", Type.INTEGER).withDefault("1").withDescription("The number of stop bits to send/expect.").withLabel("Stop Bits").withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("1", "1"), new ParameterOption("2", "2"))).build(), ConfigDescriptionParameterBuilder.create("wordLength", Type.INTEGER).withDefault("8").withDescription("The length of a serial word. Typically one byte.").withLabel("Word Length").withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("5", "5"), new ParameterOption("6", "6"), new ParameterOption("7", "7"), new ParameterOption("8", "8"))).build(), ConfigDescriptionParameterBuilder.create("flowControl", Type.INTEGER).withDefault("0").withDescription("The flow control mechanism to use. Software uses control characters in-band. Hardware uses the RTS and CTS lines.").withLabel("Flow Control").withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("0", "Off"), new ParameterOption("1", "Software"), new ParameterOption("2", "Hardware"))).build(), ConfigDescriptionParameterBuilder.create("sendBufferSize", Type.INTEGER).withDefault("5120").withDescription("The send buffer size in bytes. In total the send and receive buffers are 10240 byte (10 KiB) in size. The minimum buffer size is 1024 byte (1 KiB) each. The binding will configure the read buffer size accordingly. The send buffer holds data that is given by the user and can not be written to RS232 yet. The receive buffer holds data that is received through RS232 but could not yet be send to the user.").withLabel("Send Buffer Size").withAdvanced(true).withMinimum(BigDecimal.valueOf(1024)).withMaximum(BigDecimal.valueOf(9216)).build(), ConfigDescriptionParameterBuilder.create("frameSize", Type.INTEGER).withDefault("1").withDescription("The size of receivable data frames in bytes. Set this to something other than 1, if you want to receive data with a fix frame size. The frame readable channel will trigger every time a frame of this size is ready to be read, but will wait until this frame is read before triggering again. This means, you can use this channel as a trigger in a rule, that will read exactly one frame.").withLabel("Frame Size").withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(9216)).build(), ConfigDescriptionParameterBuilder.create("statusLEDConfig", Type.INTEGER).withDefault("3").withDescription("The status LED configuration. By default the LED shows communication traffic between Brick and Bricklet, it flickers once for every 10 received data packets.<br/><br/>You can also turn the LED permanently on/off or show a heartbeat.<br/><br/>If the Bricklet is in bootloader mode, the LED is will show heartbeat by default.").withLabel("Status LED Configuration").withAdvanced(true).withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("0", "Off"), new ParameterOption("1", "On"), new ParameterOption("2", "Show Heartbeat"), new ParameterOption("3", "Show Status"))).build())).withParameterGroups(Arrays.asList(new ConfigDescriptionParameterGroup("update_intervals", "null", true, "Update Intervals", "Update Intervals"))).build();
            case "channel-type:tinkerforge:BrickletRS232V2OverrunErrorCount":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletRS232V2ParityErrorCount":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletRS232V2SendBufferUsed":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList(ConfigDescriptionParameterBuilder.create("updateInterval", Type.INTEGER).withDefault("1000").withDescription("Specifies the update interval in milliseconds. A value of 0 disables automatic updates.").withLabel("Update Interval").withUnit("ms").build())).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletRS232V2ReceiveBufferUsed":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList(ConfigDescriptionParameterBuilder.create("updateInterval", Type.INTEGER).withDefault("1000").withDescription("Specifies the update interval in milliseconds. A value of 0 disables automatic updates.").withLabel("Update Interval").withUnit("ms").build())).withParameterGroups(Arrays.asList()).build();
            default:
                break;
        }
        return null;
    }

        @Override
    public void refreshValue(String channel, org.eclipse.smarthome.config.core.Configuration config, org.eclipse.smarthome.config.core.Configuration channelConfig, BiConsumer<String, org.eclipse.smarthome.core.types.State> updateStateFn, BiConsumer<String, String> triggerChannelFn) throws TinkerforgeException {
        BrickletRS232V2Config cfg = (BrickletRS232V2Config) config.as(BrickletRS232V2Config.class);
switch(channel) {
            case "BrickletRS232V2FrameReadable":
               return;
            case "BrickletRS232V2OverrunErrorCount":
                   {
            BrickletRS232V2.ErrorCount value = this.getErrorCount();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS232V2OverrunErrorCountGetter0(value, cfg));
        }
                   return;
            case "BrickletRS232V2ParityErrorCount":
                   {
            BrickletRS232V2.ErrorCount value = this.getErrorCount();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS232V2ParityErrorCountGetter0(value, cfg));
        }
                   return;
            case "BrickletRS232V2SendBufferUsed":
                   {
            BrickletRS232V2.BufferStatus value = this.getBufferStatus();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS232V2SendBufferUsedGetter0(value, cfg));
        }
                   return;
            case "BrickletRS232V2ReceiveBufferUsed":
                   {
            BrickletRS232V2.BufferStatus value = this.getBufferStatus();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS232V2ReceiveBufferUsedGetter0(value, cfg));
        }
                   return;
default:
                logger.warn("Refresh for unknown channel {}", channel);
                break;
        }
    }
    

        @Override
    public List<SetterRefresh> handleCommand(org.eclipse.smarthome.config.core.Configuration config, org.eclipse.smarthome.config.core.Configuration channelConfig, String channel, Command command) throws TinkerforgeException {
        List<SetterRefresh> result = Collections.emptyList();
        
        switch(channel) {
            default:
                logger.warn("Command for unknown channel {}", channel);
        }
        return result;
    }

        private String transformBrickletRS232V2FrameReadableCallback0(int frameCount, BrickletRS232V2Config cfg) {
        return "";
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS232V2OverrunErrorCountCallback0(long errorCountOverrun, long errorCountParity, BrickletRS232V2Config cfg) {
        return new DecimalType(errorCountOverrun);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS232V2ParityErrorCountCallback0(long errorCountOverrun, long errorCountParity, BrickletRS232V2Config cfg) {
        return new DecimalType(errorCountParity);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS232V2OverrunErrorCountGetter0(BrickletRS232V2.ErrorCount value, BrickletRS232V2Config cfg) {
        return new DecimalType(value.errorCountOverrun);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS232V2ParityErrorCountGetter0(BrickletRS232V2.ErrorCount value, BrickletRS232V2Config cfg) {
        return new DecimalType(value.errorCountParity);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS232V2SendBufferUsedGetter0(BrickletRS232V2.BufferStatus value, BrickletRS232V2Config cfg) {
        return new QuantityType<>(value.sendBufferUsed, SmartHomeUnits.BYTE);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS232V2ReceiveBufferUsedGetter0(BrickletRS232V2.BufferStatus value, BrickletRS232V2Config cfg) {
        return new QuantityType<>(value.receiveBufferUsed, SmartHomeUnits.BYTE);
    }

}