package ch.hevs.isi.field;

import ch.hevs.isi.core.DataPoint;
import ch.hevs.isi.core.FloatDataPoint;

import java.util.HashMap;

public abstract class ModbusRegister {
    private int address;
    /**
     * get the address of the modbus register
     * @return address of the modbus register
     */
    public int getAddress() {
        return address;
    }
    private final static HashMap<String, ModbusRegister> mapOfRegisters = new HashMap<>();      //map to store the register

    /**
     * get the modbus register from the desired datapoint
     * @param dp the desired datapoint
     * @return modbus adress of the datapoint
     */
    public static ModbusRegister getRegisterFromDatapoint(DataPoint dp){
        return mapOfRegisters.get(dp.getLabel()); //search the modbus address of the datapoint-label
    }

    /**
     * add an register to the map of the modbus addresses
     * @param label label of the datapoint
     * @param address   modbus address of the datapoint
     */
    public void updateMapOfRegisters(String label, int address){
        this.address = address;
        mapOfRegisters.put(label,this);     //add an address to the map with the corresponding datapoint-label
    }

    /**
     * read periodically each modbus register
     */
    public static void poll(){
        for (ModbusRegister mr : mapOfRegisters.values()){      //read through all the values (modbus addresses) of the map
            mr.read();      //read each datapoint, which address is stored in the map
        }
    }

    /**
     * function to read a datapoint from the modbus register
     */
    public abstract void read();        //abstract prototype of the method read

    /**
     * function to write datapoint on the modbus register
     * @param dp datapoint to write on the address
     */
    public abstract void write(DataPoint dp);       //abstract prototype of the method read
}
