/**
 * 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.BrickletSegmentDisplay4x7;
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.
 * @author Erik Fleckstein - Initial contribution
 */
@NonNullByDefault
public class BrickletSegmentDisplay4x7Wrapper extends BrickletSegmentDisplay4x7 implements StandardFlashable, DeviceWrapper {
    public static final DeviceInfo DEVICE_INFO = new DeviceInfo(BrickletSegmentDisplay4x7.DEVICE_DISPLAY_NAME, "brickletsegmentdisplay4x7", BrickletSegmentDisplay4x7.DEVICE_IDENTIFIER, BrickletSegmentDisplay4x7Wrapper.class, BrickletSegmentDisplay4x7Actions.class, "2.0.0", false);

    public BrickletSegmentDisplay4x7Wrapper(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(BrickletSegmentDisplay4x7Wrapper.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);
        
        
        
    }

    @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("BrickletSegmentDisplay4x7Brightness");
		result.add("BrickletSegmentDisplay4x7Colon");
		result.add("BrickletSegmentDisplay4x7Segments");
		result.add("BrickletSegmentDisplay4x7Text");
        return result;
    }

    public static @Nullable ChannelType getChannelType(ChannelTypeUID channelTypeUID) {
        switch(channelTypeUID.getId()) {
            case "BrickletSegmentDisplay4x7Brightness":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7Brightness"), "Brightness", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletSegmentDisplay4x7Brightness")).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 "BrickletSegmentDisplay4x7Segments":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7Segments"), "Segments", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletSegmentDisplay4x7Segments")).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_bit_order.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().withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(127)).withStep(BigDecimal.valueOf(1)).withPattern("%d").withReadOnly(false).build().toStateDescription()).build();
            case "BrickletSegmentDisplay4x7Colon":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7Colon"), "Show Colon", "Switch").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletSegmentDisplay4x7Colon")).withDescription("Turns the colon of the display on or off.").build();
            case "BrickletSegmentDisplay4x7Text":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7Text"), "Text", "String").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletSegmentDisplay4x7Text")).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 the display's colon on. For example HiTF: will show as Hi:TF on the display.").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").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 colon").withChannelDefinitions(Arrays.asList(new ChannelDefinitionBuilder("BrickletSegmentDisplay4x7Brightness", new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7Brightness")).withLabel("Brightness").build(), new ChannelDefinitionBuilder("BrickletSegmentDisplay4x7Colon", new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7Colon")).withLabel("Show Colon").build(), new ChannelDefinitionBuilder("BrickletSegmentDisplay4x7Segments", new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7Segments")).withLabel("Segments").build(), new ChannelDefinitionBuilder("BrickletSegmentDisplay4x7Text", new ChannelTypeUID("tinkerforge", "BrickletSegmentDisplay4x7Text")).withLabel("Text").build())).withProperties(props).build();
    }

    public static @Nullable ConfigDescription getConfigDescription(URI uri) {
        switch(uri.toASCIIString()) {
            case "thing-type:tinkerforge:brickletsegmentdisplay4x7":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList(new ConfigDescriptionParameterGroup("update_intervals", "null", true, "Update Intervals", "Update Intervals"))).build();
            case "channel-type:tinkerforge:BrickletSegmentDisplay4x7Brightness":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletSegmentDisplay4x7Segments":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletSegmentDisplay4x7Colon":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletSegmentDisplay4x7Text":
                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 {
        BrickletSegmentDisplay4x7Config cfg = (BrickletSegmentDisplay4x7Config) config.as(BrickletSegmentDisplay4x7Config.class);
switch(channel) {
            case "BrickletSegmentDisplay4x7Brightness":
                   {
            BrickletSegmentDisplay4x7.Segments value = this.getSegments();
            if(true)
                updateStateFn.accept(channel, transformBrickletSegmentDisplay4x7BrightnessGetter0(value, cfg));
        }
                   return;
            case "BrickletSegmentDisplay4x7Colon":
                   {
            BrickletSegmentDisplay4x7.Segments value = this.getSegments();
            if(true)
                updateStateFn.accept(channel, transformBrickletSegmentDisplay4x7ColonGetter0(value, cfg));
        }
                   return;
            case "BrickletSegmentDisplay4x7Segments":
                   {
            BrickletSegmentDisplay4x7.Segments value = this.getSegments();
            if(true)
                updateStateFn.accept(channel, transformBrickletSegmentDisplay4x7SegmentsGetter0(value, cfg));
        }
                   return;
            case "BrickletSegmentDisplay4x7Text":
               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 "BrickletSegmentDisplay4x7Brightness":
                if (command instanceof Number) {
                    Number cmd = (Number) command;
this.setSegments(this.getSegments().segments, cmd.shortValue(), this.getSegments().colon);
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of Number.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickletSegmentDisplay4x7Colon":
                if (command instanceof OnOffType) {
                    OnOffType cmd = (OnOffType) command;
this.setSegments(this.getSegments().segments, this.getSegments().brightness, cmd == OnOffType.ON);
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of OnOffType.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickletSegmentDisplay4x7Segments":
                if (command instanceof Number) {
                    Number cmd = (Number) command;
this.setSegments(new short[]{(short)(cmd.intValue() >> 24), (short)(cmd.intValue() >> 16), (short)(cmd.intValue() >> 8), (short)(cmd.intValue())}, this.getSegments().brightness, this.getSegments().colon);
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of Number.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickletSegmentDisplay4x7Text":
                if (command instanceof StringType) {
                    StringType cmd = (StringType) command;
this.setSegments(Helper.parseSegmentDisplayText(cmd.toString()), this.getSegments().brightness, 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("BrickletSegmentDisplay4x7Segments", 0));
				result.add(new SetterRefresh("BrickletSegmentDisplay4x7Colon", 0));
                break;
default:
                logger.warn("Command for unknown channel {}", channel);
        }
        return result;
    }

        private org.eclipse.smarthome.core.types.State transformBrickletSegmentDisplay4x7BrightnessGetter0(BrickletSegmentDisplay4x7.Segments value, BrickletSegmentDisplay4x7Config cfg) {
        return new DecimalType(value.brightness);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletSegmentDisplay4x7ColonGetter0(BrickletSegmentDisplay4x7.Segments value, BrickletSegmentDisplay4x7Config cfg) {
        return value.colon ? OnOffType.ON : OnOffType.OFF;
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletSegmentDisplay4x7SegmentsGetter0(BrickletSegmentDisplay4x7.Segments value, BrickletSegmentDisplay4x7Config cfg) {
        return new DecimalType((int)value.segments[0] << 24 | (int)value.segments[1] << 16 | (int)value.segments[2] << 8 | (int)value.segments[3]);
    }

}