/**
 * 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.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.StringType;

import com.tinkerforge.BrickletSegmentDisplay4x7V2;
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 Segment Display 4x7 Bricklet 2.0.
 * @author Erik Fleckstein - Initial contribution
 */
@NonNullByDefault
public class BrickletSegmentDisplay4x7V2Wrapper extends BrickletSegmentDisplay4x7V2 implements CoMCUFlashable, DeviceWrapper {
    public static final DeviceInfo DEVICE_INFO = new DeviceInfo(BrickletSegmentDisplay4x7V2.DEVICE_DISPLAY_NAME, "brickletsegmentdisplay4x7v2", BrickletSegmentDisplay4x7V2.DEVICE_IDENTIFIER, BrickletSegmentDisplay4x7V2Wrapper.class, BrickletSegmentDisplay4x7V2Actions.class, "2.0.0", true);

    public BrickletSegmentDisplay4x7V2Wrapper(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(BrickletSegmentDisplay4x7V2Wrapper.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);
        BrickletSegmentDisplay4x7V2Config cfg = (BrickletSegmentDisplay4x7V2Config) config.as(BrickletSegmentDisplay4x7V2Config.class);
        
        
		this.setStatusLEDConfig(cfg.statusLEDConfig);
    }

    @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("BrickletSegmentDisplay4x7V2Brightness");
		result.add("BrickletSegmentDisplay4x7V2ColonUpper");
		result.add("BrickletSegmentDisplay4x7V2ColonLower");
		result.add("BrickletSegmentDisplay4x7V2Tick");
		result.add("BrickletSegmentDisplay4x7V2Segments");
		result.add("BrickletSegmentDisplay4x7V2Text");
        return result;
    }

    public static @Nullable ChannelType getChannelType(ChannelTypeUID channelTypeUID) {
        switch(channelTypeUID.getId()) {
            case "BrickletSegmentDisplay4x7V2Brightness":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2Brightness"), "Brightness", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletSegmentDisplay4x7V2Brightness")).withDescription("The brightness can be set between 0 (dark) and 7 (bright).")
.withStateDescription(StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(7)).withStep(BigDecimal.valueOf(1)).withPattern("%d").withReadOnly(false).withOptions(Arrays.asList(new StateOption("0", "0"), new StateOption("1", "1"), new StateOption("2", "2"), new StateOption("3", "3"), new StateOption("4", "4"), new StateOption("5", "5"), new StateOption("6", "6"), new StateOption("7", "7"))).build().toStateDescription()).build();
            case "BrickletSegmentDisplay4x7V2Segments":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2Segments"), "Segments", "Number").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletSegmentDisplay4x7V2Segments")).withDescription("The seven segment display can be set with bitmaps. Every bit controls one segment as shown here: https://www.tinkerforge.com/en/doc/_images/bricklet_segment_display_4x7_v2_segment_index.png.. The channel accepts an integer, that is split into 4 bytes, controlling one segment each. For example 1717263183, which is 0x665b5b4f in hex will be split into 0x66 for the first segment, 0x5b for the second, 0x5b for the third and 0x4f for the fourth.")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%d %unit%").withReadOnly(false).build().toStateDescription()).build();
            case "BrickletSegmentDisplay4x7V2ColonUpper":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2ColonUpper"), "Show Upper Colon Dot", "Switch").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletSegmentDisplay4x7V2ColonUpper")).withDescription("Turns the colon of the display on or off.").build();
            case "BrickletSegmentDisplay4x7V2ColonLower":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2ColonLower"), "Show Lower Colon Dot", "Switch").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletSegmentDisplay4x7V2ColonLower")).withDescription("Turns the colon of the display on or off.").build();
            case "BrickletSegmentDisplay4x7V2Tick":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2Tick"), "Show Tick", "Switch").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletSegmentDisplay4x7V2Tick")).withDescription("Turns the colon of the display on or off.").build();
            case "BrickletSegmentDisplay4x7V2Text":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2Text"), "Text", "String").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletSegmentDisplay4x7V2Text")).withDescription("Text to display on the seven segment display. Supported are A-Z, a-z, 0-9, \", (, ), +, -, =, [, ], ^, _ and |. An unsupported character will show as empty. A colon (:) anywhere in the text will light on the display's colon. Alternatively, you can enable only the upper colon dot with a backtick (`) or the lower one with a comma (,). An apostrophe (') anywhere will light up the tick after the third digit. A dot (.) after another character will light the corresponding digit's dot. For example H.i,T.'F will show HiTF on the display and activate the first and third dot, lower colon dot and the tick.").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 Segment Display 4x7 Bricklet 2.0").isListed(false).withSupportedBridgeTypeUIDs(Arrays.asList(TinkerforgeBindingConstants.THING_TYPE_BRICK_DAEMON.toString())).withConfigDescriptionURI(URI.create("thing-type:tinkerforge:" + thingTypeUID.getId())).withDescription("Four 7-segment displays with switchable dots").withChannelDefinitions(Arrays.asList(new ChannelDefinitionBuilder("BrickletSegmentDisplay4x7V2Brightness", new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2Brightness")).withLabel("Brightness").build(), new ChannelDefinitionBuilder("BrickletSegmentDisplay4x7V2ColonUpper", new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2ColonUpper")).withLabel("Show Upper Colon Dot").build(), new ChannelDefinitionBuilder("BrickletSegmentDisplay4x7V2ColonLower", new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2ColonLower")).withLabel("Show Lower Colon Dot").build(), new ChannelDefinitionBuilder("BrickletSegmentDisplay4x7V2Tick", new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2Tick")).withLabel("Show Tick").build(), new ChannelDefinitionBuilder("BrickletSegmentDisplay4x7V2Segments", new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2Segments")).withLabel("Segments").build(), new ChannelDefinitionBuilder("BrickletSegmentDisplay4x7V2Text", new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7V2Text")).withLabel("Text").build())).withProperties(props).build();
    }

    public static @Nullable ConfigDescription getConfigDescription(URI uri) {
        switch(uri.toASCIIString()) {
            case "thing-type:tinkerforge:brickletsegmentdisplay4x7v2":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList(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:BrickletSegmentDisplay4x7V2Brightness":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletSegmentDisplay4x7V2Segments":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletSegmentDisplay4x7V2ColonUpper":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletSegmentDisplay4x7V2ColonLower":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletSegmentDisplay4x7V2Tick":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletSegmentDisplay4x7V2Text":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).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 {
        BrickletSegmentDisplay4x7V2Config cfg = (BrickletSegmentDisplay4x7V2Config) config.as(BrickletSegmentDisplay4x7V2Config.class);
switch(channel) {
            case "BrickletSegmentDisplay4x7V2Brightness":
                   {
            int value = this.getBrightness();
            if(true)
                updateStateFn.accept(channel, transformBrickletSegmentDisplay4x7V2BrightnessGetter0(value, cfg));
        }
                   return;
            case "BrickletSegmentDisplay4x7V2ColonUpper":
                   {
            boolean value = this.getSelectedSegment(32);
            if(true)
                updateStateFn.accept(channel, transformBrickletSegmentDisplay4x7V2ColonUpperGetter0(value, cfg));
        }
                   return;
            case "BrickletSegmentDisplay4x7V2ColonLower":
                   {
            boolean value = this.getSelectedSegment(33);
            if(true)
                updateStateFn.accept(channel, transformBrickletSegmentDisplay4x7V2ColonLowerGetter0(value, cfg));
        }
                   return;
            case "BrickletSegmentDisplay4x7V2Tick":
                   {
            boolean value = this.getSelectedSegment(34);
            if(true)
                updateStateFn.accept(channel, transformBrickletSegmentDisplay4x7V2TickGetter0(value, cfg));
        }
                   return;
            case "BrickletSegmentDisplay4x7V2Segments":
                   {
            BrickletSegmentDisplay4x7V2.Segments value = this.getSegments();
            if(true)
                updateStateFn.accept(channel, transformBrickletSegmentDisplay4x7V2SegmentsGetter0(value, cfg));
        }
                   return;
            case "BrickletSegmentDisplay4x7V2Text":
               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 = new ArrayList<SetterRefresh>();
        
        switch(channel) {
            case "BrickletSegmentDisplay4x7V2Brightness":
                if (command instanceof Number) {
                    Number cmd = (Number) command;
this.setBrightness(cmd.shortValue());
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of Number.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickletSegmentDisplay4x7V2ColonUpper":
                if (command instanceof OnOffType) {
                    OnOffType cmd = (OnOffType) command;
this.setSelectedSegment(32, cmd == OnOffType.ON);
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of OnOffType.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickletSegmentDisplay4x7V2ColonLower":
                if (command instanceof OnOffType) {
                    OnOffType cmd = (OnOffType) command;
this.setSelectedSegment(33, cmd == OnOffType.ON);
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of OnOffType.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickletSegmentDisplay4x7V2Tick":
                if (command instanceof OnOffType) {
                    OnOffType cmd = (OnOffType) command;
this.setSelectedSegment(34, cmd == OnOffType.ON);
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of OnOffType.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickletSegmentDisplay4x7V2Segments":
                if (command instanceof Number) {
                    Number cmd = (Number) command;
this.setSegments(Helper.shortToBits((short)(cmd.intValue() >> 24)), Helper.shortToBits((short)(cmd.intValue() >> 16)), Helper.shortToBits((short)(cmd.intValue() >> 8)), Helper.shortToBits((short)cmd.intValue()), this.getSegments().colon, this.getSegments().tick);
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of Number.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickletSegmentDisplay4x7V2Text":
                if (command instanceof StringType) {
                    StringType cmd = (StringType) command;
this.setSegments(Helper.parseSegmentDisplay2TextDigit(cmd.toString(), 0), Helper.parseSegmentDisplay2TextDigit(cmd.toString(), 1), Helper.parseSegmentDisplay2TextDigit(cmd.toString(), 2), Helper.parseSegmentDisplay2TextDigit(cmd.toString(), 3), new boolean[]{cmd.toString().contains("`") || cmd.toString().contains(":"), cmd.toString().contains(",") || cmd.toString().contains(":")}, cmd.toString().contains("'"));
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of StringType.", command.getClass().getName(), channel);
                }
                result.add(new SetterRefresh("BrickletSegmentDisplay4x7V2Segments", 0));
				result.add(new SetterRefresh("BrickletSegmentDisplay4x7V2ColonUpper", 0));
				result.add(new SetterRefresh("BrickletSegmentDisplay4x7V2ColonLower", 0));
				result.add(new SetterRefresh("BrickletSegmentDisplay4x7V2Tick", 0));
                break;
default:
                logger.warn("Command for unknown channel {}", channel);
        }
        return result;
    }

        private org.eclipse.smarthome.core.types.State transformBrickletSegmentDisplay4x7V2BrightnessGetter0(int value, BrickletSegmentDisplay4x7V2Config cfg) {
        return new DecimalType(value);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletSegmentDisplay4x7V2ColonUpperGetter0(boolean value, BrickletSegmentDisplay4x7V2Config cfg) {
        return value ? OnOffType.ON : OnOffType.OFF;
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletSegmentDisplay4x7V2ColonLowerGetter0(boolean value, BrickletSegmentDisplay4x7V2Config cfg) {
        return value ? OnOffType.ON : OnOffType.OFF;
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletSegmentDisplay4x7V2TickGetter0(boolean value, BrickletSegmentDisplay4x7V2Config cfg) {
        return value ? OnOffType.ON : OnOffType.OFF;
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletSegmentDisplay4x7V2SegmentsGetter0(BrickletSegmentDisplay4x7V2.Segments value, BrickletSegmentDisplay4x7V2Config cfg) {
        return new DecimalType((Helper.bitsToLong(value.digit0) << 24) | (Helper.bitsToLong(value.digit0) << 16) | (Helper.bitsToLong(value.digit0) << 8) | Helper.bitsToLong(value.digit0));
    }

}