from channels import Group as channelsGroup
from channels.sessions import channel_session
import random
import json
import channels
import logging

from otree import constants_internal
import django.test
from otree.common_internal import (get_admin_secret_code)
from .models import Subsession as OtreeSubsession, Player as OtreePlayer

client = django.test.Client()
ADMIN_SECRET_CODE = get_admin_secret_code()


#############################################
# Socket for the MC-Conf
#############################################
# Connected to websocket.connect
def conf_exp_main_ws_mc_connect(message):
    print("*********CONNECT_ConfExp_MC************")
    channelsGroup("ws_confexp_mc").add(message.reply_channel)


# Connected to websocket.receive
def conf_exp_main_ws_mc_message(message):
    print("*********RECEIVE_ConfExp_MC************")
    # Decrypt the url: No info in the url in this app
    # Decrypt the received message
    jsonmessage = json.loads(message.content['text'])
    subsession_pk = jsonmessage['subsession_pk']
    mysubsession = OtreeSubsession.objects.get(pk=subsession_pk)
    order = jsonmessage['order']
    if order == "DeleteQuestion":
        question_text = jsonmessage['param1']
        mysubsession.delete_question(question_text)
        #############################################
        # Give feedback
        channelsGroup("ws_confexp_mc").send({'text': json.dumps(
            {"order": "refresh"})}
        )
    elif order == "refresh_all_participants":
        channelsGroup("ws_confexp_allparticipants").send({'text': json.dumps(
            {"order": "refresh"})}
        )
    elif order == "refresh_xp_iframe":
        channelsGroup("ws_confexp_allparticipants").send({'text': json.dumps(
            {"order": "refresh_xp_iframe"})}
        )
    elif order == "toggle_blocking_on_inner_xp_frame":
        if mysubsession.participants_navigation_possibilities == "_Discussion__Experience__Results_":
            mysubsession.participants_navigation_possibilities = "_Experience_"
        elif mysubsession.participants_navigation_possibilities == "_Experience_":
            mysubsession.participants_navigation_possibilities = "_Discussion__Experience__Results_"
        mysubsession.save()
        # Update the participants to limit their navigation
        channelsGroup("ws_confexp_allparticipants").send({'text': json.dumps(
            {"order": "refresh"})}
        )
        # Update the MC to inform him
        channelsGroup("ws_confexp_mc").send({'text': json.dumps(
            {"order": "refresh_participants_navigation_possibilities",
             "participants_nav_poss": mysubsession.participants_navigation_possibilities})}
        )
    elif order == "DetermineWinner":
        winner_id = mysubsession.determine_winner(subsession_pk)
        # Give feedback
        channelsGroup("ws_confexp_mc").send({'text': json.dumps(
            {"order": "refresh_winner_information",})}
        )
    elif ((order == "InformWinnerResult") & ('winner_id' in mysubsession.session.vars)):
        textforwinnerpage = json.dumps({
            "order": "announce_winner",
            "winner_id": mysubsession.session.vars['winner_id'],
        })
        channelsGroup("ws_confexp_allparticipants").send({'text': textforwinnerpage})
        mysubsession.computation_locked = True
        mysubsession.save()
        # Give feedback
        channelsGroup("ws_confexp_mc").send({'text': json.dumps(
            {"order": "refresh_winner_information",
             "winner_id": mysubsession.winner_id,})}
        )
    elif order == "UnlockWinnerDetermination":
        mysubsession.computation_locked = False
        mysubsession.save()
        # Give feedback
        channelsGroup("ws_confexp_mc").send({'text': json.dumps(
            {"order": "refresh_winner_information",
             "winner_id": mysubsession.winner_id,})}
        )
    # Manage the deactivation of the players on a particular page
    elif order == "deactivate_all_players_on_page":
        page_name = jsonmessage['page_name']
        round_nb = jsonmessage['round_nb']
        for p in mysubsession.get_players():
            # Set player one page further
            if ((str(p.participant._current_page_name) == page_name)
                    & (p.participant._round_number == round_nb)):
                p.participant.vars['participant_is_active'] = 'Inactive'
                p.participant.save()
    # Manage the reactivation of the players on a particular page
    elif order == "reactivate_all_players_on_page":
        page_name = jsonmessage['page_name']
        round_nb = jsonmessage['round_nb']
        for p in mysubsession.get_players():
            # Set player one page further
            if ((str(p.participant._current_page_name) == page_name)
                    & (p.participant._round_number == round_nb)):
                p.participant.vars['participant_is_active'] = 'answering_questionnaire'
                p.participant.save()


# Connected to websocket.disconnect
def conf_exp_main_ws_mc_disconnect(message):
    print("*********DISCONNECT_ConfExp_MC************")
    channelsGroup("ws_confexp_mc").discard(message.reply_channel)


#############################################
# Socket for the whole conference
#############################################
# Connected to websocket.connect
def conf_exp_main_ws_whole_conf_connect(message):
    print("*********CONNECT_ConfExp_WholeConf************")
    channelsGroup("ws_confexp_wholeconf").add(message.reply_channel)


# Connected to websocket.receive
def conf_exp_main_ws_whole_conf_message(message):
    print("*********RECEIVE_ConfExp_WholeConf************")
    jsonmessage = json.loads(message.content['text'])
    subsession_pk = jsonmessage['subsession_pk']
    mysubsession = OtreeSubsession.objects.get(pk=subsession_pk)
    order = jsonmessage['order']


# Connected to websocket.disconnect
def conf_exp_main_ws_whole_conf_disconnect(message):
    print("*********DISCONNECT_ConfExp_WholeConf************")
    channelsGroup("ws_confexp_wholeconf").discard(message.reply_channel)


#############################################
# Socket for all the participants
#############################################
# Connected to websocket.connect
def conf_exp_main_ws_allparticipants_connect(message):
    print("*********CONNECT_ConfExp_AllParticipants************")
    channelsGroup("ws_confexp_allparticipants").add(message.reply_channel)

# Connected to websocket.receive
def conf_exp_main_ws_allparticipants_message(message):
    print("*********RECEIVE_ConfExp_AllParticipants************")
    jsonmessage = json.loads(message.content['text'])
    order = jsonmessage['order']
    if order == "send_message":
        player_pk = jsonmessage['player_pk']
        myplayer = OtreePlayer.objects.get(pk=player_pk)
        myplayer.message = str(myplayer.message) + " - " + str(jsonmessage['message'])
        myplayer.save()

# Connected to websocket.disconnect
def conf_exp_main_ws_allparticipants_disconnect(message):
    print("*********DISCONNECT_ConfExp_AllParticipants************")
    channelsGroup("ws_confexp_allparticipants").discard(message.reply_channel)
