import time
import requests
from util.buzzer import beep
from util.pir import detect
from util.chatbot import chat
from util.photo import take_and_judge_photo
from util.dht import get_environment_data
from util.recorder import record_and_recognize

DHT = 4
BUZZER = 21
DETECTOR = 24
USER = 'SXKDZ'

global flag
flag = False


def log_message(message, is_self=True):
    if is_self is True:
        print('# ' + message)
    else:
        print('> ' + message)


def send_message(message, is_self=True):
    log_message(message, is_self)
    url = 'http://120.24.80.95:8090/add-sentence/%s' % USER
    payload = {
        'user': USER if is_self is True else 'Other',
        'content': message
    }
    requests.post(url, params=payload)


def control_screen(is_on):
    log_message('screen is ' + ('on' if is_on is True else 'off'), False)
    url = 'http://120.24.80.95:8090/set/%s' % USER
    payload = {
        'key': 'screenOn',
        'val': 'true' if is_on is True else 'false'
    }
    requests.get(url, params=payload)


def set_temperature_humidity(temperature, humidity):
    url = 'http://120.24.80.95:8090/set/%s' % USER
    payload = {
        'key': 'temperature'
        'val': '%s' % temperature
    }
    requests.get(url, params=payload)
    payload = {
        'key': 'humidity'
        'val': '%s' % humidity
    }
    requests.get(url, params=payload)


def welcome():
    global flag
    flag = True
    control_screen(True)
    welcome_message = '您好，%s！' % USER
    send_message(welcome_message, False)
    now_time = int(time.strftime("%H", time.localtime()))
    if now_time > 23 or now_time < 5:
        response_message = '这么晚了还不睡吗？'
        send_message(response_message, False)
    elif 6 <= now_time <= 7:
        response_message = '您起的真早！'
        send_message(response_message, False)
    face_score = take_and_judge_photo()
    if face_score.get('error', None) is not None:
        control_screen(False)
        flag = False
    else:
        if float(face_score['neutral']) > 0.5\
            or float(face_score['anger']) > 0.5\
            or float(face_score['disgust'] > 0.5):
            emotion_message = '您今天看上去不太开心呢！'
            response_message = chat('我今天不太开心')
            send_message(emotion_message, False)
            send_message(response_message, False)
        elif float(face_score['surprise']) > 0.5:
            emotion_message = '您看上去有小惊喜！'
            send_message(emotion_message, False)
        elif float(face_score['happiness']) > 0.5:
            emotion_message = '您看上去很开心哦！'
            response_message = chat('我今天很开心哦！')
            send_message(emotion_message, False)
            send_message(response_message, False)
        elif float(face_score['sadness']) > 0.5:
            emotion_message = '有什么烦恼就尽管和我说吧'
            response_message = chat('今天我特别忧伤')
            send_message(emotion_message, False)
            send_message(response_message, False)
        else:
            emotion_message = '看不出来您在想什么……真是个神秘的人呐……'
            send_message(emotion_message, False)


def main():
    global flag
    while True:
        time.sleep(0.2)
        if flag == True:
            if detect(DETECTOR) == 1:
                text = record_and_recognize()
                if text.get('error', None) is not None:
                    response_message = '您说啥？没听清……'
                    send_message(response_message, False)
                else:
                    send_message(text['text'])
                    response_message = chat(text['text'])
                    send_message(response_message, False)
                    if text['text'] == '再见':
                        flag = False
            else:
                control_screen(False)
        else:
            welcome()


if __name__ == '__main__':
    main()
