package com.fizz.business.comm.iot;

import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * 基于 iot-communication 的 S7 写入客户端（仅用于写入）。
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "iot.communication", name = "enabled", havingValue = "true")
public class S7WriteClient {

    @Value("${iot.communication.s7.ip:127.0.0.1}")
    private String ip;

    @Value("${iot.communication.s7.port:102}")
    private int port;

    @Value("${iot.communication.s7.rack:0}")
    private int rack;

    @Value("${iot.communication.s7.slot:1}")
    private int slot;

    @Value("${iot.communication.s7.plc-type:S1200}")
    private String plcType;

    public S7PLC newClient() {
        EPlcType type = parsePlcType(plcType);
        return new S7PLC(type, ip, port, rack, slot);
    }

    private EPlcType parsePlcType(String value) {
        try {
            return EPlcType.valueOf(value.trim().toUpperCase(Locale.ROOT));
        } catch (Exception e) {
            log.warn("未知 plc-type: {}，回退到 S1200", value);
            return EPlcType.S1200;
        }
    }
}
