from extronlib import event, Version
from atlasied_atmosphere_v_1_0_0 import CommandProcessor
from extronlib.system import Wait, MESet
from extronlib.device import UIDevice, ProcessorDevice
from extronlib.ui import Button, Slider, Label, Level
from math import floor

print(Version())

AtlasIED = CommandProcessor()
AtlasIED.IPAddress = '192.168.196.74'

CurrentPopup = None

"""

As of this writing, there is no way to retrieve a list of key/value pairs for controls with the AtlasIED. We encourage
you to create a dictionary of key/value pairs that map to the qualifier values that will be used to satisfy a request.
This is demonstrated below, and will be used throughout the program.

"""

ControlMapping = {
    'Room A Mic': {
        'Source': '0'
    },
    'Room B Mic': {
        'Source': '1'
    },
    'Mic Mix': {
        'Mix': '14'
    },
    'Zone 1': {
        'Zone': '0'
    },
    'Zone 2': {
        'Zone': '1'
    },
    'AB Combined': {
        'Group': '0'
    },
    'Emergency Alert': {
        'PlayMessage': '0'
    },
    'Fire Alarm': {
        'PlayMessage': '1'
    },
    'Startup Scene': {
        'RecallScene': '0'
    },
    'Shutdown Scene': {
        'RecallScene': '1'
    },
    'All Hands Meeting': {
        'RecallRoutine': '0',
    },
    'Holiday Shutdown': {
        'RecallRoutine': '1'
    },
    'Amp Off': {
        'RecallGpoPreset': '0'
    },
    'Amp On': {
        'RecallGpoPreset': '1'
    },
    'No Bell Schedule': '0',
    'Monday Bell Schedule': '1',
    'Wednesday Bell Schedule': '2',
    'Friday Bell Schedule': '3'
}

# Device Definitions -------------------------------------------------------------------------------------------------

AtlasIEDAtmosphereTLP = UIDevice('AtlasIEDAtmosphereTLP')
AtlasIEDAtmosphereIPCP = ProcessorDevice('AtlasIEDAtmosphereIPCP')

AtlasIEDAtmosphereTLP.ShowPage('Main')
AtlasIEDAtmosphereTLP.ShowPopup('Logo')

# Navigation Definitions ---------------------------------------------------------------------------------------------

InputsOutputsNavigation = Button(AtlasIEDAtmosphereTLP, 10)
ActionsNavigation = Button(AtlasIEDAtmosphereTLP, 11)
TodaysBellScheduleNavigation = Button(AtlasIEDAtmosphereTLP, 12)
StateFeedbackNavigation = Button(AtlasIEDAtmosphereTLP, 13)

NavigationButtons = MESet([
    InputsOutputsNavigation,
    ActionsNavigation,
    TodaysBellScheduleNavigation,
    StateFeedbackNavigation
])

NavigationButtons.SetCurrent(None)

NavigationItems = {
    10: 'Inputs/Outputs',
    11: 'Actions',
    12: 'Bell Schedule',
    13: 'State Feedback'
}


@event(NavigationButtons.Objects, 'Pressed')
def __nav_btn_pressed(button, _):
    global CurrentPopup
    status = AtlasIED.ReadStatus('GroupActive', ControlMapping['AB Combined'])
    NavigationButtons.SetCurrent(button)
    CurrentPopup = NavigationItems[button.ID]
    if CurrentPopup == 'Inputs/Outputs' and status == 'On':
        AtlasIEDAtmosphereTLP.ShowPopup('Inputs/Outputs Combined')
    else:
        AtlasIEDAtmosphereTLP.ShowPopup(NavigationItems[button.ID])


# Inputs Controls Start  ----------------------------------------------------------------------------------------------

VolumeEventsList = ['Tapped', 'Released', 'Pressed', 'Repeated']

# Volume Buttons

SourceOneVolumeUp = Button(AtlasIEDAtmosphereTLP, 17, repeatTime=0.3)
SourceOneVolumeDown = Button(AtlasIEDAtmosphereTLP, 18, repeatTime=0.3)

SourceTwoVolumeUp = Button(AtlasIEDAtmosphereTLP, 25, repeatTime=0.3)
SourceTwoVolumeDown = Button(AtlasIEDAtmosphereTLP, 26, repeatTime=0.3)

ZoneOneVolumeUp = Button(AtlasIEDAtmosphereTLP, 44, repeatTime=0.3)
ZoneOneVolumeDown = Button(AtlasIEDAtmosphereTLP, 45, repeatTime=0.3)

MixOneVolumeUp = Button(AtlasIEDAtmosphereTLP, 36, repeatTime=0.3)
MixOneVolumeDown = Button(AtlasIEDAtmosphereTLP, 37, repeatTime=0.3)

ZoneTwoVolumeUp = Button(AtlasIEDAtmosphereTLP, 52, repeatTime=0.3)
ZoneTwoVolumeDown = Button(AtlasIEDAtmosphereTLP, 53, repeatTime=0.3)

GroupOneVolumeUp = Button(AtlasIEDAtmosphereTLP, 61, repeatTime=0.3)
GroupOneVolumeDown = Button(AtlasIEDAtmosphereTLP, 62, repeatTime=0.3)

# Volume Sliders

SourceOneVolumeSlider = Slider(AtlasIEDAtmosphereTLP, 14)
SourceTwoVolumeSlider = Slider(AtlasIEDAtmosphereTLP, 31)

ZoneOneVolumeSlider = Slider(AtlasIEDAtmosphereTLP, 41)
ZoneTwoVolumeSlider = Slider(AtlasIEDAtmosphereTLP, 76)

MixOneVolumeSlider = Slider(AtlasIEDAtmosphereTLP, 33)

GroupOneVolumeSlider = Slider(AtlasIEDAtmosphereTLP, 58)

SourceOneVolumeSlider.SetRange(-80, 0, 5)
SourceTwoVolumeSlider.SetRange(-80, 0, 5)
ZoneOneVolumeSlider.SetRange(-80, 0, 5)
ZoneTwoVolumeSlider.SetRange(-80, 0, 5)
GroupOneVolumeSlider.SetRange(-80, 0, 5)
MixOneVolumeSlider.SetRange(-80, 0, 5)

# Volume Labels

SourceOneDBLabel = Label(AtlasIEDAtmosphereTLP, 21)
SourceTwoDBLabel = Label(AtlasIEDAtmosphereTLP, 28)

SourceOnePercentLabel = Label(AtlasIEDAtmosphereTLP, 22)
SourceTwoPercentLabel = Label(AtlasIEDAtmosphereTLP, 29)

ZoneOneDBLabel = Label(AtlasIEDAtmosphereTLP, 48)
ZoneTwoDBLabel = Label(AtlasIEDAtmosphereTLP, 55)

ZoneOnePercentLabel = Label(AtlasIEDAtmosphereTLP, 49)
ZoneTwoPercentLabel = Label(AtlasIEDAtmosphereTLP, 56)

MixOneDBLabel = Label(AtlasIEDAtmosphereTLP, 40)
MixOnePercentLabel = Label(AtlasIEDAtmosphereTLP, 39)

GroupOneDBLabel = Label(AtlasIEDAtmosphereTLP, 64)
GroupOnePercentLabel = Label(AtlasIEDAtmosphereTLP, 65)

# Mute Buttons

SourceOneMuteButton = Button(AtlasIEDAtmosphereTLP, 19)
SourceTwoMuteButton = Button(AtlasIEDAtmosphereTLP, 27)
MixOneMuteButton = Button(AtlasIEDAtmosphereTLP, 38)
ZoneOneMuteButton = Button(AtlasIEDAtmosphereTLP, 46)
ZoneTwoMuteButton = Button(AtlasIEDAtmosphereTLP, 54)
GroupOneMuteButton = Button(AtlasIEDAtmosphereTLP, 63)

# Zone Source Buttons

ZoneOneSourceNone = Button(AtlasIEDAtmosphereTLP, 107)
ZoneOneSourceRoomAMic = Button(AtlasIEDAtmosphereTLP, 68)
ZoneOneSourceRoomBMic = Button(AtlasIEDAtmosphereTLP, 69)
ZoneOneSourceMicMix = Button(AtlasIEDAtmosphereTLP, 67)

ZoneTwoSourceNone = Button(AtlasIEDAtmosphereTLP, 109)
ZoneTwoSourceRoomAMic = Button(AtlasIEDAtmosphereTLP, 73)
ZoneTwoSourceRoomBMic = Button(AtlasIEDAtmosphereTLP, 74)
ZoneTwoSourceMicMix = Button(AtlasIEDAtmosphereTLP, 72)

GroupSourceNone = Button(AtlasIEDAtmosphereTLP, 114)
GroupSourceRoomAMic = Button(AtlasIEDAtmosphereTLP, 77)
GroupSourceRoomBMic = Button(AtlasIEDAtmosphereTLP, 79)
GroupSourceMicMix = Button(AtlasIEDAtmosphereTLP, 71)

# Zone Grouped Buttons

ZoneOneGroupedIndicator = Button(AtlasIEDAtmosphereTLP, 110)
ZoneTwoGroupedIndicator = Button(AtlasIEDAtmosphereTLP, 112)
GroupActiveToggle = Button(AtlasIEDAtmosphereTLP, 81)

# Labels

SourceOneNameLabel = Label(AtlasIEDAtmosphereTLP, 16)
SourceTwoNameLabel = Label(AtlasIEDAtmosphereTLP, 24)
MixOneNameLabel = Label(AtlasIEDAtmosphereTLP, 35)
ZoneOneNameLabel = Label(AtlasIEDAtmosphereTLP, 43)
ZoneTwoNameLabel = Label(AtlasIEDAtmosphereTLP, 51)
GroupOneNameLabel = Label(AtlasIEDAtmosphereTLP, 60)

# Meters

SourceOneMeter = Level(AtlasIEDAtmosphereTLP, 15)
SourceTwoMeter = Level(AtlasIEDAtmosphereTLP, 23)
MixOneMeter = Level(AtlasIEDAtmosphereTLP, 34)
ZoneOneMeter = Level(AtlasIEDAtmosphereTLP, 42)
ZoneTwoMeter = Level(AtlasIEDAtmosphereTLP, 50)
GroupOneMeter = Level(AtlasIEDAtmosphereTLP, 59)

SourceOneMeter.SetRange(-80, 0, Step=1)
SourceTwoMeter.SetRange(-80, 0, Step=1)
MixOneMeter.SetRange(-80, 0, Step=1)
ZoneOneMeter.SetRange(-80, 0, Step=1)
ZoneTwoMeter.SetRange(-80, 0, Step=1)
GroupOneMeter.SetRange(-80, 0, Step=1)

# Button Lists

ZoneOneSourceButtons = MESet([
    ZoneOneSourceNone,
    ZoneOneSourceRoomAMic,
    ZoneOneSourceRoomBMic,
    ZoneOneSourceMicMix
])

ZoneTwoSourceButtons = MESet([
    ZoneTwoSourceNone,
    ZoneTwoSourceRoomAMic,
    ZoneTwoSourceRoomBMic,
    ZoneTwoSourceMicMix
])

GroupSourceButtons = MESet([
    GroupSourceNone,
    GroupSourceRoomAMic,
    GroupSourceRoomBMic,
    GroupSourceMicMix
])

VolumeUpButtons = [
    ZoneTwoVolumeUp,
    ZoneOneVolumeUp,
    MixOneVolumeUp,
    SourceOneVolumeUp,
    SourceTwoVolumeUp,
    GroupOneVolumeUp
]

VolumeDownButtons = [
    ZoneOneVolumeDown,
    ZoneTwoVolumeDown,
    MixOneVolumeDown,
    SourceOneVolumeDown,
    SourceTwoVolumeDown,
    GroupOneVolumeDown
]

VolumeMuteButtons = [
    SourceOneMuteButton,
    SourceTwoMuteButton,
    MixOneMuteButton,
    ZoneOneMuteButton,
    ZoneTwoMuteButton,
    GroupOneMuteButton
]

SourceSliderMap = {
    '0': {
        'Slider': SourceOneVolumeSlider,
        'DB': SourceOneDBLabel,
        'Percentage': SourceOnePercentLabel
    },
    '1': {
        'Slider': SourceTwoVolumeSlider,
        'DB': SourceTwoDBLabel,
        'Percentage': SourceTwoPercentLabel
    }
}

ZoneSliderMap = {
    '0': {
        'Slider': ZoneOneVolumeSlider,
        'DB': ZoneOneDBLabel,
        'Percentage': ZoneOnePercentLabel
    },
    '1': {
        'Slider': ZoneTwoVolumeSlider,
        'DB': ZoneTwoDBLabel,
        'Percentage': ZoneTwoPercentLabel
    }
}


# Callback definitions

def MapChanges(slider, db, percent, value):
    slider.SetFill(value)
    value = floor(value)
    db.SetText('{0} dB'.format(value))
    d = abs(slider.Max - slider.Min)
    p = abs(slider.Min - value) / d
    percent.SetText("{:.0%}".format(p))


def SourceSliderCallback(command, value, qualifier):
    global SourceSliderMap
    try:
        source = SourceSliderMap[qualifier.get('Source', None)]
        slider = source['Slider']
        db = source['DB']
        percent = source['Percentage']
        value = float(value)
        MapChanges(slider, db, percent, value)
    except (KeyError, Exception) as err:
        print('{0} is err'.format(str(err)))


def MixSliderCallback(command, value, qualifier):
    global MixOneVolumeSlider
    global MixOneDBLabel
    global MixOnePercentLabel
    value = float(value)
    MapChanges(MixOneVolumeSlider, MixOneDBLabel, MixOnePercentLabel, value)


def ZoneSliderCallback(command, value, qualifier):
    global ZoneSliderMap
    try:
        zone = ZoneSliderMap[qualifier.get('Zone', None)]
        slider = zone['Slider']
        db = zone['DB']
        percent = zone['Percentage']
        value = float(value)
        MapChanges(slider, db, percent, value)
    except (KeyError, Exception) as err:
        print('{0} is err'.format(str(err)))


def GroupSliderCallback(command, value, qualifier):
    global GroupOneVolumeSlider
    global GroupOneDBLabel
    global GroupOnePercentLabel
    value = float(value)
    MapChanges(GroupOneVolumeSlider, GroupOneDBLabel, GroupOnePercentLabel, value)


def SourceMuteCallback(command, value, qualifier):
    global SourceOneMuteButton
    global SourceTwoMuteButton
    source = qualifier.get('Source', None)
    if source is not None:
        if source == '0':
            if value == 'On':
                SourceOneMuteButton.SetState(1)
            else:
                SourceOneMuteButton.SetState(0)
        elif source == '1':
            if value == 'On':
                SourceTwoMuteButton.SetState(1)
            else:
                SourceTwoMuteButton.SetState(0)


def ZoneMuteCallback(command, value, qualifier):
    global ZoneOneMuteButton
    global ZoneTwoMuteButton
    zone = qualifier.get('Zone', None)
    if zone is not None:
        if zone == '0':
            if value == 'On':
                ZoneOneMuteButton.SetState(1)
            else:
                ZoneOneMuteButton.SetState(0)
        elif zone == '1':
            if value == 'On':
                ZoneTwoMuteButton.SetState(1)
            else:
                ZoneTwoMuteButton.SetState(0)


def MixMuteCallback(command, value, qualifier):
    global MixOneMuteButton
    if value == 'On':
        MixOneMuteButton.SetState(1)
    else:
        MixOneMuteButton.SetState(0)


def GroupMuteCallback(command, value, qualifier):
    global GroupOneMuteButton
    if value == 'On':
        GroupOneMuteButton.SetState(1)
    else:
        GroupOneMuteButton.SetState(0)


def ZoneOneSourceCallback(command, value, qualifier):
    if value is None:
        ZoneOneSourceButtons.SetCurrent(0)
    else:
        value = int(value)
        if value == 0:
            ZoneOneSourceButtons.SetCurrent(1)
        elif value == 1:
            ZoneOneSourceButtons.SetCurrent(2)
        elif value == 14:
            ZoneOneSourceButtons.SetCurrent(3)


def ZoneTwoSourceCallback(command, value, qualifier):
    if value is None:
        ZoneTwoSourceButtons.SetCurrent(0)
    else:
        value = int(value)
        if value == 0:
            ZoneTwoSourceButtons.SetCurrent(1)
        elif value == 1:
            ZoneTwoSourceButtons.SetCurrent(2)
        elif value == 14:
            ZoneTwoSourceButtons.SetCurrent(3)


def GroupSourceCallback(command, value, qualifier):
    if value is None:
        GroupSourceButtons.SetCurrent(0)
    else:
        value = int(value)
        if value == 0:
            GroupSourceButtons.SetCurrent(1)
        if value == 1:
            GroupSourceButtons.SetCurrent(2)
        if value == 14:
            GroupSourceButtons.SetCurrent(3)


def ZoneGroupedCallback(command, value, qualifier):
    global ZoneOneGroupedIndicator
    global ZoneTwoGroupedIndicator
    zone = qualifier.get('Zone', None)
    if zone is not None:
        if zone == '0':
            if value == 'On':
                ZoneOneGroupedIndicator.SetState(0)
            else:
                ZoneOneGroupedIndicator.SetState(1)
        elif zone == '1':
            if value == 'On':
                ZoneTwoGroupedIndicator.SetState(0)
            else:
                ZoneTwoGroupedIndicator.SetState(1)


def GroupActiveCallback(command, value, qualifier):
    global GroupActiveToggle
    if value == 'On':
        if CurrentPopup == 'Inputs/Outputs':
            AtlasIEDAtmosphereTLP.ShowPopup('Inputs/Outputs Combined')
        GroupActiveToggle.SetState(1)
    else:
        if CurrentPopup == 'Inputs/Outputs':
            AtlasIEDAtmosphereTLP.ShowPopup('Inputs/Outputs')
        GroupActiveToggle.SetState(0)


def ControlNameCallback(command, value, qualifier):
    group = qualifier.get('Group', None)
    if group is not None:
        GroupOneNameLabel.SetText(value)
    source = qualifier.get('Source', None)
    if source is not None:
        if source == '0':
            SourceOneNameLabel.SetText(value)
        elif source == '1':
            SourceTwoNameLabel.SetText(value)
    mix = qualifier.get('Mix', None)
    if mix is not None:
        MixOneNameLabel.SetText(value)
    zone = qualifier.get('Zone', None)
    if zone is not None:
        if zone == '0':
            ZoneOneNameLabel.SetText(value)
        elif zone == '1':
            ZoneTwoNameLabel.SetText(value)


def MeterCallback(command, value, qualifier):
    group = qualifier.get('Group', None)
    if group is not None:
        GroupOneMeter.SetLevel(float(value))
    source = qualifier.get('Source', None)
    if source is not None:
        if source == '0':
            SourceOneMeter.SetLevel(float(value))
        elif source == '1':
            SourceTwoMeter.SetLevel(float(value))
    mix = qualifier.get('Mix', None)
    if mix is not None:
        MixOneMeter.SetLevel(float(value))
    zone = qualifier.get('Zone', None)
    if zone is not None:
        if zone == '0':
            ZoneOneMeter.SetLevel(float(value))
        elif zone == '1':
            ZoneTwoMeter.SetLevel(float(value))


# SubscribeStatus registrations

AtlasIED.SubscribeStatus('Level', SourceSliderCallback, ControlMapping['Room A Mic'])
AtlasIED.SubscribeStatus('Level', SourceSliderCallback, ControlMapping['Room B Mic'])
AtlasIED.SubscribeStatus('Level', MixSliderCallback, ControlMapping['Mic Mix'])
AtlasIED.SubscribeStatus('Level', ZoneSliderCallback, ControlMapping['Zone 1'])
AtlasIED.SubscribeStatus('Level', ZoneSliderCallback, ControlMapping['Zone 2'])
AtlasIED.SubscribeStatus('Level', GroupSliderCallback, ControlMapping['AB Combined'])

AtlasIED.SubscribeStatus('Mute', ZoneMuteCallback, ControlMapping['Zone 1'])
AtlasIED.SubscribeStatus('Mute', ZoneMuteCallback, ControlMapping['Zone 2'])
AtlasIED.SubscribeStatus('Mute', GroupMuteCallback, ControlMapping['AB Combined'])
AtlasIED.SubscribeStatus('Mute', SourceMuteCallback, ControlMapping['Room A Mic'])
AtlasIED.SubscribeStatus('Mute', SourceMuteCallback, ControlMapping['Room B Mic'])
AtlasIED.SubscribeStatus('Mute', MixMuteCallback, ControlMapping['Mic Mix'])

AtlasIED.SubscribeStatus('Source', ZoneOneSourceCallback, ControlMapping['Zone 1'])
AtlasIED.SubscribeStatus('Source', ZoneTwoSourceCallback, ControlMapping['Zone 2'])
AtlasIED.SubscribeStatus('Source', GroupSourceCallback, ControlMapping['AB Combined'])

AtlasIED.SubscribeStatus('ZoneGrouped', ZoneGroupedCallback, ControlMapping['Zone 1'])
AtlasIED.SubscribeStatus('ZoneGrouped', ZoneGroupedCallback, ControlMapping['Zone 2'])

AtlasIED.SubscribeStatus('GroupActive', GroupActiveCallback, ControlMapping['AB Combined'])

AtlasIED.SubscribeStatus('ControlName', ControlNameCallback, ControlMapping['Mic Mix'])
AtlasIED.SubscribeStatus('ControlName', ControlNameCallback, ControlMapping['Room A Mic'])
AtlasIED.SubscribeStatus('ControlName', ControlNameCallback, ControlMapping['Room B Mic'])
AtlasIED.SubscribeStatus('ControlName', ControlNameCallback, ControlMapping['Zone 1'])
AtlasIED.SubscribeStatus('ControlName', ControlNameCallback, ControlMapping['Zone 2'])
AtlasIED.SubscribeStatus('ControlName', ControlNameCallback, ControlMapping['AB Combined'])

AtlasIED.SubscribeStatus('Meter', MeterCallback, ControlMapping['Mic Mix'])
AtlasIED.SubscribeStatus('Meter', MeterCallback, ControlMapping['Room A Mic'])
AtlasIED.SubscribeStatus('Meter', MeterCallback, ControlMapping['Room B Mic'])
AtlasIED.SubscribeStatus('Meter', MeterCallback, ControlMapping['Zone 1'])
AtlasIED.SubscribeStatus('Meter', MeterCallback, ControlMapping['Zone 2'])
AtlasIED.SubscribeStatus('Meter', MeterCallback, ControlMapping['AB Combined'])


# Event Definitions

@event(GroupActiveToggle, 'Pressed')
def __group_active_pressed(button, state):
    if button.State == 1:
        AtlasIED.Set('GroupActive', 'Off', ControlMapping['AB Combined'])
    else:
        AtlasIED.Set('GroupActive', 'On', ControlMapping['AB Combined'])


@event(GroupSourceButtons.Objects, 'Pressed')
def __group_source_button_press(button, state):
    value = None
    if button.ID == 114:
        value = '-1'
    elif button.ID == 77:
        value = ControlMapping['Room A Mic']['Source']
    elif button.ID == 79:
        value = ControlMapping['Room B Mic']['Source']
    elif button.ID == 71:
        value = ControlMapping['Mic Mix']['Mix']
    AtlasIED.Set('Source', value, ControlMapping['AB Combined'])


@event(ZoneOneSourceButtons.Objects, 'Pressed')
def __zone_one_source_button_press(button, state):
    value = None
    if button.ID == 107:
        value = '-1'
    elif button.ID == 68:
        value = ControlMapping['Room A Mic']['Source']
    elif button.ID == 69:
        value = ControlMapping['Room B Mic']['Source']
    elif button.ID == 67:
        value = ControlMapping['Mic Mix']['Mix']
    AtlasIED.Set('Source', value, ControlMapping['Zone 1'])


@event(ZoneTwoSourceButtons.Objects, 'Pressed')
def __zone_two_source_button_press(button, state):
    value = None
    if button.ID == 109:
        value = '-1'
    elif button.ID == 73:
        value = ControlMapping['Room A Mic']['Source']
    elif button.ID == 74:
        value = ControlMapping['Room B Mic']['Source']
    elif button.ID == 72:
        value = ControlMapping['Mic Mix']['Mix']
    AtlasIED.Set('Source', value, ControlMapping['Zone 2'])


@event(VolumeMuteButtons, 'Pressed')
def __mute_press_event(button, state):
    qualifier = None
    if button.ID == 19:
        qualifier = ControlMapping['Room A Mic']
    elif button.ID == 27:
        qualifier = ControlMapping['Room B Mic']
    elif button.ID == 38:
        qualifier = ControlMapping['Mic Mix']
    elif button.ID == 46:
        qualifier = ControlMapping['Zone 1']
    elif button.ID == 54:
        qualifier = ControlMapping['Zone 2']
    elif button.ID == 63:
        qualifier = ControlMapping['AB Combined']
    if button.State == 1:
        AtlasIED.Set('Mute', 'Off', qualifier)
    else:
        AtlasIED.Set('Mute', 'On', qualifier)


@event(VolumeUpButtons, VolumeEventsList)
def __source_vol_up_event(button, state):
    if state == 'Pressed' or state == 'Repeated':
        qualifier = None
        if button.State != 1:
            button.SetState(1)
        if button.ID == 17:
            qualifier = ControlMapping['Room A Mic']
        elif button.ID == 25:
            qualifier = ControlMapping['Room B Mic']
        elif button.ID == 36:
            qualifier = ControlMapping['Mic Mix']
        elif button.ID == 44:
            qualifier = ControlMapping['Zone 1']
        elif button.ID == 52:
            qualifier = ControlMapping['Zone 2']
        elif button.ID == 61:
            qualifier = ControlMapping['AB Combined']
        AtlasIED.Set('LevelRamp', '5', qualifier)
    else:
        button.SetState(0)


@event(VolumeDownButtons, VolumeEventsList)
def __source_vol_down_event(button, state):
    if state == 'Pressed' or state == 'Repeated':
        qualifier = None
        if button.State != 1:
            button.SetState(1)
        if button.ID == 18:
            qualifier = ControlMapping['Room A Mic']
        elif button.ID == 26:
            qualifier = ControlMapping['Room B Mic']
        elif button.ID == 37:
            qualifier = ControlMapping['Mic Mix']
        elif button.ID == 45:
            qualifier = ControlMapping['Zone 1']
        elif button.ID == 53:
            qualifier = ControlMapping['Zone 2']
        elif button.ID == 62:
            qualifier = ControlMapping['AB Combined']
        AtlasIED.Set('LevelRamp', '-5', qualifier)
    else:
        button.SetState(0)


@event([
    SourceOneVolumeSlider,
    SourceTwoVolumeSlider,
    MixOneVolumeSlider,
    ZoneOneVolumeSlider,
    ZoneTwoVolumeSlider,
    GroupOneVolumeSlider
],
    'Released')
def __source_slider_release_event(slider, state, value):
    qualifier = None
    if slider.ID == 14:
        qualifier = ControlMapping['Room A Mic']
    elif slider.ID == 31:
        qualifier = ControlMapping['Room B Mic']
    elif slider.ID == 33:
        qualifier = ControlMapping['Mic Mix']
    elif slider.ID == 41:
        qualifier = ControlMapping['Zone 1']
    elif slider.ID == 76:
        qualifier = ControlMapping['Zone 2']
    elif slider.ID == 58:
        qualifier = ControlMapping['AB Combined']
    AtlasIED.Set('Level', value, qualifier)


# Inputs Controls End  ------------------------------------------------------------------------------------------------

# Actions Controls Start ----------------------------------------------------------------------------------------------


EmergencyAlertButton = Button(AtlasIEDAtmosphereTLP, 84)
FireAlarmButton = Button(AtlasIEDAtmosphereTLP, 85)

StartupSceneButton = Button(AtlasIEDAtmosphereTLP, 87)
ShutdownSceneButton = Button(AtlasIEDAtmosphereTLP, 88)

AllHandsMeetingButton = Button(AtlasIEDAtmosphereTLP, 90)
HolidayShutdownButton = Button(AtlasIEDAtmosphereTLP, 91)

AmpOffPresetButton = Button(AtlasIEDAtmosphereTLP, 93)
AmpOnPresetButton = Button(AtlasIEDAtmosphereTLP, 94)

MessageButtons = [
    EmergencyAlertButton,
    FireAlarmButton
]

SceneButtons = [
    StartupSceneButton,
    ShutdownSceneButton
]

RoutineButtons = [
    AllHandsMeetingButton,
    HolidayShutdownButton
]

GPOPresetButtons = [
    AmpOffPresetButton,
    AmpOnPresetButton
]


@event(MessageButtons, ['Released', 'Pressed'])
def __message_button_pressed(button, state):
    if state == 'Pressed':
        button.SetState(1)
        if button.ID == 84:
            AtlasIED.Set('Action', None, ControlMapping['Emergency Alert'])
        elif button.ID == 85:
            AtlasIED.Set('Action', None, ControlMapping['Fire Alarm'])
    elif state == 'Released':
        button.SetState(0)


@event(SceneButtons, ['Released', 'Pressed'])
def __scene_button_pressed(button, state):
    if state == 'Pressed':
        button.SetState(1)
        if button.ID == 87:
            AtlasIED.Set('Action', None, ControlMapping['Startup Scene'])
        elif button.ID == 88:
            AtlasIED.Set('Action', None, ControlMapping['Shutdown Scene'])
    elif state == 'Released':
        button.SetState(0)


@event(RoutineButtons, ['Released', 'Pressed'])
def __scene_button_pressed(button, state):
    if state == 'Pressed':
        button.SetState(1)
        if button.ID == 90:
            AtlasIED.Set('Action', None, ControlMapping['All Hands Meeting'])
        elif button.ID == 91:
            AtlasIED.Set('Action', None, ControlMapping['Holiday Shutdown'])
    elif state == 'Released':
        button.SetState(0)


@event(GPOPresetButtons, ['Pressed', 'Released'])
def __gpo_preset_button_pressed(button, state):
    if state == 'Pressed':
        button.SetState(1)
        if button.ID == 93:
            AtlasIED.Set('Action', None, ControlMapping['Amp Off'])
        elif button.ID == 94:
            AtlasIED.Set('Action', None, ControlMapping['Amp On'])
    elif state == 'Released':
        button.SetState(0)


# Action Controls End -------------------------------------------------------------------------------------------------


# Bell Schedule Controls Start ----------------------------------------------------------------------------------------

NoBellScheduleButton = Button(AtlasIEDAtmosphereTLP, 103)
MondayBellScheduleButton = Button(AtlasIEDAtmosphereTLP, 96)
TuesdayBellScheduleButton = Button(AtlasIEDAtmosphereTLP, 97)
FridayBellScheduleButton = Button(AtlasIEDAtmosphereTLP, 98)

BellScheduleMESet = MESet([
    NoBellScheduleButton,
    MondayBellScheduleButton,
    TuesdayBellScheduleButton,
    FridayBellScheduleButton
])


def BellScheduleCallback(command, value, qualifier):
    global BellScheduleMESet
    if value == ControlMapping['No Bell Schedule']:
        BellScheduleMESet.SetCurrent(0)
    elif value == ControlMapping['Monday Bell Schedule']:
        BellScheduleMESet.SetCurrent(1)
    elif value == ControlMapping['Wednesday Bell Schedule']:
        BellScheduleMESet.SetCurrent(2)
    elif value == ControlMapping['Friday Bell Schedule']:
        BellScheduleMESet.SetCurrent(3)


@event(BellScheduleMESet.Objects, 'Pressed')
def __bell_schedule_button_pressed(button, state):
    if button.ID == 103:
        AtlasIED.Set('BellSchedule', ControlMapping['No Bell Schedule'], None)
    elif button.ID == 96:
        AtlasIED.Set('BellSchedule', ControlMapping['Monday Bell Schedule'], None)
    elif button.ID == 97:
        AtlasIED.Set('BellSchedule', ControlMapping['Wednesday Bell Schedule'], None)
    elif button.ID == 98:
        AtlasIED.Set('BellSchedule', ControlMapping['Friday Bell Schedule'], None)


AtlasIED.SubscribeStatus('BellSchedule', BellScheduleCallback, None)

# Bell Schedule Controls End ------------------------------------------------------------------------------------------


# Top Level Buttons Start ---------------------------------------------------------------------------------------------

EnableDebugButton = Button(AtlasIEDAtmosphereTLP, 4)
ReinitializeButton = Button(AtlasIEDAtmosphereTLP, 3)
InitializedIndicator = Button(AtlasIEDAtmosphereTLP, 7)
CommunicatingButton = Button(AtlasIEDAtmosphereTLP, 6)
EnableMeteringButton = Button(AtlasIEDAtmosphereTLP, 5)
InitializedIndicator.SetState(1)


def ResetMeterLevels(val):
    MixOneMeter.SetLevel(val)
    SourceOneMeter.SetLevel(val)
    SourceTwoMeter.SetLevel(val)
    ZoneOneMeter.SetLevel(val)
    ZoneTwoMeter.SetLevel(val)
    GroupOneMeter.SetLevel(val)


@event(EnableMeteringButton, 'Pressed')
def __enable_metering_pressed(button, state):
    if button.State == 0:
        button.SetState(1)
        AtlasIED.Set('Meter', 'On', ControlMapping['Room A Mic'])
        AtlasIED.Set('Meter', 'On', ControlMapping['Room B Mic'])
        AtlasIED.Set('Meter', 'On', ControlMapping['Zone 1'])
        AtlasIED.Set('Meter', 'On', ControlMapping['Zone 2'])
        AtlasIED.Set('Meter', 'On', ControlMapping['AB Combined'])
        AtlasIED.Set('Meter', 'On', ControlMapping['Mic Mix'])
    elif button.State == 1:
        button.SetState(0)
        AtlasIED.Set('Meter', 'Off', ControlMapping['Room A Mic'])
        AtlasIED.Set('Meter', 'Off', ControlMapping['Room B Mic'])
        AtlasIED.Set('Meter', 'Off', ControlMapping['Zone 1'])
        AtlasIED.Set('Meter', 'Off', ControlMapping['Zone 2'])
        AtlasIED.Set('Meter', 'Off', ControlMapping['AB Combined'])
        AtlasIED.Set('Meter', 'Off', ControlMapping['Mic Mix'])

        @Wait(2.5)
        def __reset_levels():
            ResetMeterLevels(-80)


@event(AtlasIED, 'Communicating')
def __is_communicating(cp, state):
    if state is True:
        CommunicatingButton.SetState(0)
    elif state is False:
        CommunicatingButton.SetState(1)


@event(AtlasIED, 'Initialized')
def __initialized_event(cp, state):
    if state is True:
        InitializedIndicator.SetState(0)
    elif state is False:
        InitializedIndicator.SetState(1)


@event(AtlasIED, 'DebugEnabled')
def __debug_enabled(cp, state):
    if state is True:
        EnableDebugButton.SetState(1)
    elif state is False:
        EnableDebugButton.SetState(0)


@event(EnableDebugButton, 'Pressed')
def __enable_debug_pressed(button, state):
    if AtlasIED.Debug is True:
        AtlasIED.Debug = False
    elif AtlasIED.Debug is False:
        AtlasIED.Debug = True


@event(ReinitializeButton, ['Pressed', 'Released'])
def __reinitialize_button_event(button, state):
    if state == 'Pressed':
        button.SetState(1)
    elif state == 'Released':
        button.SetState(0)
    AtlasIED.Reinitialize()


# State Feedback Components Start -------------------------------------------------------------------------------------

GPOStateFeedbackOne = Button(AtlasIEDAtmosphereTLP, 105)
GPOStateFeedbackTwo = Button(AtlasIEDAtmosphereTLP, 106)
LoudNoiseFeedback = Button(AtlasIEDAtmosphereTLP, 104)


def LoudNoiseCallback(command, value, qualifier):
    if value == 'On':
        LoudNoiseFeedback.SetState(0)
    elif value == 'Off':
        LoudNoiseFeedback.SetState(1)


def GPOStateCallback(command, value, qualifier):
    gpo = qualifier.get('Gpo', None)
    if gpo is not None:
        if gpo == '0':
            if value == 'On':
                GPOStateFeedbackOne.SetState(0)
            elif value == 'Off':
                GPOStateFeedbackOne.SetState(1)
        elif gpo == '1':
            if value == 'On':
                GPOStateFeedbackTwo.SetState(0)
            elif value == 'Off':
                GPOStateFeedbackTwo.SetState(1)


AtlasIED.SubscribeStatus('GPOState', GPOStateCallback, {
    'Gpo': '0'
})

AtlasIED.SubscribeStatus('GPOState', GPOStateCallback, {
    'Gpo': '1'
})

AtlasIED.SubscribeStatus('LoudNoise', LoudNoiseCallback, None)


def Initialize():
    AtlasIED.Debug = True
    AtlasIED.Connect()


Initialize()
