# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division, unicode_literals
import os

import logging
from timeit import default_timer
from random import choice
import time

import requests

from ameise import app, ask, log
from utils import write_text_matrix

from flask_ask import Ask, statement, question, session, context

ALEXA_DEVICE2ROOM = {
    'amzn1.ask.device.AGUM4ZB75QPFGNC5X2TYPIACRGBGQJUG7W3EJYVOG7W46XYQLQJNH3OJAUYPRZKMWDDE2UJGFJWSWCM27F4D22LD2PC6T3CAZEJB5ZQPIBY6NA32MIITTNUCTUL5SOIV5RDC2HWHI6UJRN77G7CFT2TPZB6A':
        'arbeitszimmer',
    'amzn1.ask.device.AGUM4ZB75QPFGNC5X2TYPIACRGBPSS5LVRD657YFVYBPGW2VGO2TZTHMZVAUBLBDSBKCTZ5P5MOXX5S5DLDEKPQAIOSQLQOI2SXIF2X6HT5GMJELOUNWZEXNM44SCT4CQBNTC73WDCW3KNX75PFXNFR7GRVA':
        'wohnzimmer',
    }

# room powerswitch ids
ROOM2POWER_DOMO_IDX = {
    'arbeitszimmer': 2839,
    'wohnzimmer': 2840,
}

class RoomState(object):
    def __init__(self):
        self.last_switches = {}
        for room in ROOM2POWER_DOMO_IDX:
            self.last_switches[room] = time.time()


STATE = RoomState()

# map alexa slot to domoticz switch value
ON_OFF_SLOT = {'an': 'On', 'aus': 'Off'}


DOMO_ALEXA_AUTH = ('alexa', os.environ['DOMO_ALEXA_PW'])
DOMO_BASE = 'https://domo.cere.duckdns.org/json.htm'

def domo_command(**kwargs):
    t = default_timer()
    try:
        kwargs['type'] = 'command'
        resp = requests.get(DOMO_BASE, params=kwargs, auth=DOMO_ALEXA_AUTH)
        if resp.status_code == 200:
            return resp.json()
        else:
            raise ValueError('code: %s' % resp.status_code)
    finally:
        log.info('domo call in %.3f sec' % (default_timer()-t))


@ask.intent("LightIntent")
def toggle_switch(OnOff):

    did = context.System.device.get('deviceId')
    room = ALEXA_DEVICE2ROOM.get(did)
    if room is None:
        return statement('Sorry, Ich weiss nicht wo du bist')

    log.info('alexa: room %s switch: %s' % (room, OnOff))

    assert OnOff in ON_OFF_SLOT, OnOff
    switchcmd = ON_OFF_SLOT[OnOff]

    domo_idx = ROOM2POWER_DOMO_IDX[room]

    log.info('domoticz: device %s switch: %s' % (domo_idx, switchcmd))

    domo_command(param='switchlight', idx=domo_idx, switchcmd=switchcmd)

    delta_last = time.time() - STATE.last_switches[room]
    STATE.last_switches[room] = time.time()

    if delta_last < 30:
        return statement('')
    else:
        if choice(range(10)) == 0:
            return statement('Ich habe das Licht im %s %sgeschaltet.' % (room, OnOff))
        else:
            return statement('OK')
