package com.usky.rule.vo.log;

import com.usky.rule.util.JsonUtil;
import java.util.List;
import java.util.Map;
import org.jetbrains.annotations.NotNull;

public class ActionControlSerialization implements RuleEngineLogSerialization<ControlAction> {
    public ActionControlSerialization() {
    }

    public ControlAction serialize(String detail) {
        return null;
    }

    public Content toContent(Object obj) {
        if (obj instanceof Map) {
            ControlAction controlAction = (ControlAction)JsonUtil.toObject((Map)obj, ControlAction.class);
            return getContent(controlAction);
        } else if (obj instanceof ControlAction) {
            return getContent((ControlAction)obj);
        } else {
            throw new ClassCastException("ActionControlSerialization不支持该类型的转换");
        }
    }

    @NotNull
    private static Content getContent(ControlAction controlAction) {
        Content content = new Content();
        List<DeviceControlResult> devices = controlAction.getDevices();
        List<Control> controls = controlAction.getControls();
        StringBuilder builder = new StringBuilder();

        for(int j = 0; j < devices.size(); ++j) {
            DeviceControlResult deviceControlResult = (DeviceControlResult)devices.get(j);
            if (j > 0) {
                builder.append("\n");
            }

            builder.append(deviceControlResult.getName()).append("：");
            List<DeviceControlResult.Result> results = deviceControlResult.getResult();

            for(int i = 0; i < results.size(); ++i) {
                DeviceControlResult.Result result = (DeviceControlResult.Result)results.get(i);
                String resultDesc = "失败";
                if (i > 0) {
                    builder.append("，");
                }

                if ("0".equals(result.getCode()) || "200".equals(result.getCode())) {
                    resultDesc = "成功";
                }

                Control control = (Control)controls.get(i);
                builder.append(control.getName()).append("设置为：").append(control.getValueDesc()).append("(").append(resultDesc).append(")");
            }
        }

        content.setContent(builder.toString());
        content.setTime(controlAction.getTime());
        return content;
    }

    public String getType() {
        return "action:deviceControl";
    }
}
