package wa.server.plugin.nutups;

import wa.server.plugin.WAStatus;
import zutil.io.file.FileUtil;
import zutil.osal.app.linux.NutUPSClient;
import zutil.parser.DataNode;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Ziver on 2016-04-02.
 */
public class UPSStatus implements WAStatus {

    private NutUPSClient nutClient;


    public UPSStatus(){
        nutClient = new NutUPSClient("192.168.1.110", NutUPSClient.DEFAULT_PORT);
    }


    @Override
    public String getName() {
        return "UPS Status";
    }

    @Override
    public String html() {
        try {
            return FileUtil.getContent(FileUtil.findURL("wa/server/plugin/nutups/UPSStatus.tmpl"));
        } catch (IOException e) {
            return e.getMessage();
        }
    }

    @Override
    public void jsonUpdate(Map<String, String> request, DataNode root) {
        if(request.containsKey("ups")) {
            DataNode upsRoot = new DataNode(DataNode.DataType.List);
            for (NutUPSClient.UPSDevice ups : nutClient.getUPSList()){
                DataNode upsNode = new DataNode(DataNode.DataType.Map);
                upsNode.set("id", ups.getId());
                upsNode.set("model", ups.getModelName());
                upsNode.set("desc", ups.getDescription());
                upsNode.set("charge", ups.getBatteryCharge());
                upsNode.set("load", ups.getPowerLoad());
                upsNode.set("power_usage", ups.getPowerUsage());

                upsRoot.add(upsNode);
            }
            root.set("ups", upsRoot);
        }
    }
}
