/*
 * Copyright (c) 2010-2026 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
 */
package org.openhab.binding.shelly.internal;

import static org.openhab.binding.shelly.internal.ShellyBindingConstants.DEFAULT_LOCAL_PORT;
import static org.openhab.binding.shelly.internal.ShellyDevices.*;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
import org.openhab.binding.shelly.internal.api2.Shelly2RpcSocket;
import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
import org.openhab.binding.shelly.internal.config.ShellyBindingRuntimeConfig;
import org.openhab.binding.shelly.internal.handler.ShellyBaseHandler;
import org.openhab.binding.shelly.internal.handler.ShellyBluHandler;
import org.openhab.binding.shelly.internal.handler.ShellyLightHandler;
import org.openhab.binding.shelly.internal.handler.ShellyManagerInterface;
import org.openhab.binding.shelly.internal.handler.ShellyProtectedHandler;
import org.openhab.binding.shelly.internal.handler.ShellyRelayHandler;
import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
import org.openhab.binding.shelly.internal.handler.ShellyThingTable;
import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
import org.openhab.core.io.net.http.HttpClientFactory;
import org.openhab.core.io.net.http.WebSocketFactory;
import org.openhab.core.net.HttpServiceUtil;
import org.openhab.core.net.NetworkAddressService;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.binding.BaseThingHandlerFactory;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerFactory;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.ComponentException;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The {@link ShellyHandlerFactory} is responsible for creating things and thing handlers.
 *
 * @author Markus Michels - Initial contribution
 */
@NonNullByDefault
@Component(service = { ThingHandlerFactory.class, ShellyHandlerFactory.class }, configurationPid = "binding.shelly")
public class ShellyHandlerFactory extends BaseThingHandlerFactory {
    private final Logger logger = LoggerFactory.getLogger(ShellyHandlerFactory.class);
    private final HttpClient httpClient;
    private final ShellyTranslationProvider messages;
    private final Shelly1CoapServer coapServer;
    private final ShellyThingTable thingTable;
    private final WebSocketClient webSocketClient;
    private final ShellyBindingRuntimeConfig bindingConfig;

    /**
     * Activate the bundle: save properties
     *
     * @param componentContext
     * @param configProperties set of properties from cfg (use same names as in
     *            thing config)
     */
    @Activate
    public ShellyHandlerFactory(@Reference NetworkAddressService networkAddressService,
            @Reference ShellyTranslationProvider translationProvider, @Reference ShellyThingTable thingTable,
            @Reference HttpClientFactory httpClientFactory, @Reference WebSocketFactory webSocketFactory,
            ComponentContext componentContext, Map<String, Object> configProperties) {
        super.activate(componentContext);
        this.messages = translationProvider;
        this.thingTable = thingTable;
        WebSocketClient client = Shelly2RpcSocket.createWebSocketClient(webSocketFactory, "shelly2api");
        this.webSocketClient = client;
        try {
            client.start();
        } catch (Exception e) {
            logger.error("Failed to start ShellyHandlerFactory WebSocketClient: {}", e.getMessage(), e);
            throw new ComponentException("Failed to activate: Unable to start WebSocket client: " + e.getMessage(), e);
        }

        ShellyBindingConfiguration rawConfig = ShellyBindingConfiguration.fromProperties(configProperties);
        this.httpClient = httpClientFactory.getCommonHttpClient();
        int httpPort = HttpServiceUtil.getHttpServicePort(componentContext.getBundleContext());
        logger.debug("Using OH HTTP port {}", httpPort != -1 ? httpPort : DEFAULT_LOCAL_PORT);
        this.bindingConfig = new ShellyBindingRuntimeConfig(rawConfig, httpPort, networkAddressService);
        if (bindingConfig.getLocalIP().isBlank()) {
            logger.error("{}", messages.get("init.noipaddress"));
        }

        this.coapServer = new Shelly1CoapServer();
        this.thingTable.startDiscoveryService(bundleContext);
    }

    @Deactivate
    public void deactivate() {
        try {
            webSocketClient.stop();
        } catch (Exception e) {
            logger.warn("Failed to stop ShellyHandlerFactory WebSocketClient: {}", e.getMessage(), e);
        }
    }

    @Override
    public boolean supportsThingType(ThingTypeUID thingTypeUID) {
        return SUPPORTED_THING_TYPES.contains(thingTypeUID);
    }

    @Override
    protected @Nullable ThingHandler createHandler(Thing thing) {
        ThingTypeUID thingTypeUID = thing.getThingTypeUID();
        ShellyBaseHandler handler = null;

        if (THING_TYPE_SHELLYPROTECTED.equals(thingTypeUID)) {
            logger.debug("{}: Create new thing of type {} using ShellyProtectedHandler", thing.getLabel(),
                    thingTypeUID.toString());
            handler = new ShellyProtectedHandler(thing, messages, bindingConfig, thingTable, coapServer, httpClient,
                    webSocketClient);
        } else if (GROUP_LIGHT_THING_TYPES.contains(thingTypeUID)) {
            logger.debug("{}: Create new thing of type {} using ShellyLightHandler", thing.getLabel(),
                    thingTypeUID.toString());
            handler = new ShellyLightHandler(thing, messages, bindingConfig, thingTable, coapServer, httpClient,
                    webSocketClient);
        } else if (GROUP_BLU_THING_TYPES.contains(thingTypeUID)) {
            logger.debug("{}: Create new thing of type {} using ShellyBluSensorHandler", thing.getLabel(),
                    thingTypeUID.toString());
            handler = new ShellyBluHandler(thing, messages, bindingConfig, thingTable, coapServer, httpClient,
                    webSocketClient);
        } else if (SUPPORTED_THING_TYPES.contains(thingTypeUID)) {
            logger.debug("{}: Create new thing of type {} using ShellyRelayHandler", thing.getLabel(),
                    thingTypeUID.toString());
            handler = new ShellyRelayHandler(thing, messages, bindingConfig, thingTable, coapServer, httpClient,
                    webSocketClient);
        }

        if (handler != null) {
            String uid = thing.getUID().getAsString();
            thingTable.addThing(uid, handler);
            logger.debug("Thing handler for uid {} added, total things = {}", uid, thingTable.size());
            return handler;
        }
        logger.debug("Unable to create Thing Handler instance!");
        return null;
    }

    /**
     * Remove handler of things.
     */
    @Override
    protected synchronized void removeHandler(ThingHandler thingHandler) {
        if (thingHandler instanceof ShellyBaseHandler shellyBaseHandler) {
            shellyBaseHandler.stop();
            String uid = thingHandler.getThing().getUID().getAsString();
            thingTable.removeThing(uid);
        }
    }

    /**
     * Dispatch event to registered devices.
     *
     * @param deviceName
     * @param componentIndex Index of component, e.g. 2 for relay2
     * @param eventType Type of event, e.g. light
     * @param parameters Input parameters from URL, e.g. on sensor reports
     */
    public void onEvent(String ipAddress, String deviceName, String componentIndex, String eventType,
            Map<String, String> parameters) {
        logger.trace("{}: Dispatch event to thing handler", deviceName);
        for (Map.Entry<String, ShellyThingInterface> listener : thingTable.getAll().entrySet()) {
            ShellyBaseHandler thingHandler = (ShellyBaseHandler) listener.getValue();
            if (thingHandler.onEvent(ipAddress, deviceName, componentIndex, eventType, parameters)) {
                // event processed
                return;
            }
        }
    }

    public ShellyBindingRuntimeConfig getBindingConfig() {
        return bindingConfig;
    }

    public Map<String, ShellyManagerInterface> getThingHandlers() {
        Map<String, ShellyManagerInterface> table = new HashMap<>();
        for (Map.Entry<String, ShellyThingInterface> entry : thingTable.getAll().entrySet()) {
            table.put(entry.getKey(), (ShellyManagerInterface) entry.getValue());
        }
        return table;
    }
}
