import logging

from isobus.common import NumericValue
from isobus.ibsinterface import IBSInterface
from isobus.common import IBSID
from isobus.constants import *
from isobus.log import log
from isobus.common import IBSException


class IBSVTInterface(IBSInterface):
    """ Implements ISOBUS part 6 funcationality (Version 3)
    Extends the ISOBUS general interface
    """

    def WaitForStatusMessage(self, vtsa):
        return self._WaitForIBSMessage(PGN_VT2ECU, vtsa, 0xFF, 0xFE)

    def SendChangeActiveMask(self, wsid, maskid, sa, da):
        candata = ([0xAD] 
        + NumericValue(wsid).AsLEBytes(2) 
        + NumericValue(maskid).AsLEBytes(2)
        + [0xFF, 0xFF, 0xFF])

        self._SendIBSMessage(PGN_ECU2VT, da, sa, candata)

    def WaitForChangeActiveMaskResponse(self, vtsa, ecusa):
        [received, data] = self._WaitForIBSMessage(PGN_VT2ECU, vtsa, ecusa, 0xAD)
        return received, NumericValue.FromLEBytes(data[1:3]).Value(), data[3]

    def SendChangeSKMask(self, maskid, skmaskid, alarm, vtsa, ecusa):
        candata = [0xFF] * 8
        if alarm:
            candata = ([0xAE] 
            + [0x02] 
            + NumericValue(maskid).AsLEBytes(2)
            + NumericValue(skmaskid).AsLEBytes(2)
            + [0xFF, 0xFF])
        else:
            candata = ([0xAE] 
            + [0x01] 
            + NumericValue(maskid).AsLEBytes(2)
            + NumericValue(skmaskid).AsLEBytes(2)
            + [0xFF, 0xFF])

        self._SendIBSMessage(PGN_ECU2VT, vtsa, ecusa, candata)

    def WaitForChangeSKMaskResponse(self, vtsa, ecusa):
        """ Wait for the Change Soft Key Mask response message
        Return True for received, error code, and new SK mask ID
        """
        [received, data] = self._WaitForIBSMessage(PGN_VT2ECU, vtsa, ecusa, 0xAE)
        return received, data[5], NumericValue.FromLEBytes(data[3:5]).Value()


    def SendChangeAttribute(self, objid, attrid, value, vtsa, ecusa):
        candata = ([0xAF]
                + NumericValue(objid).AsLEBytes(2)
                + NumericValue(attrid).AsLEBytes(1)
                + NumericValue(value).AsLEBytes(4))

        self._SendIBSMessage(PGN_ECU2VT, vtsa, ecusa, candata)

    def WaitChangeAttributeResponse(self, vtsa, ecusa):