import json

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from django.contrib.auth.models import User
from muzak.auth import get_user_from_token
from channels.db import database_sync_to_async
from playlist.models import Session, Track, Vote
import random


class SessionConsumer(WebsocketConsumer):
	def connect(self):
		self.session_id = self.scope["url_route"]["kwargs"]["session_id"]
		self.session_name = f"session_{self.session_id}"

		async_to_sync(self.channel_layer.group_add)(
			self.session_name, self.channel_name
		)
		self.accept()

	def disconnect(self, close_code):
		# Leave room group
		async_to_sync(self.channel_layer.group_discard)(
			self.session_name, self.channel_name
		)

	# Receive message from WebSocket
	def receive(self, text_data):
		user = self.scope["user"] # Waarschijnlijk altijd AnonymousUser
		print(self.scope)
		sessionId = self.scope["url_route"].get("kwargs", {}).get("session_id", None)
		print()

		text_data_json = json.loads(text_data)

		# Niet lachen, middleware is moeilijk oké?
		token = text_data_json.get("token")
		if token:
			user = get_user_from_token(token, log=True)
		print(user)
		session = Session.objects.get(session_id=sessionId)

		action = text_data_json.get("action", None)
		if action == "message":
			message = text_data_json["message"]
			# Send message to room group
			async_to_sync(self.channel_layer.group_send)(
				self.session_name, {"type": "chat.message", "message": str(user) + ": " + message}
			)
		if action == "login":
			print("LOGIN", str(user))
			async_to_sync(self.channel_layer.group_send)(
				self.session_name, {"type": "announce", "user": str(user)}
			)
		if action == "vote":
			points = text_data_json.get("points", None)
			track = session.current_track;
			try:
				vote = Vote.objects.get(user=user, track=track, session=session)
				vote.points = points
				vote.save()
			except Vote.DoesNotExist:
				vote = Vote.objects.create(user=user, track=track, points=points, session=session)
				vote.save()
		if action == "pause":
			pass
		if action == "next":
			random.seed(session.seed)
			tracks = Track.objects.order_by("?")
			next = False
			if session.current_track:
				for track in tracks:
					if next:
						session.current_track = track
						break
					if session.current_track == track:
						next = True
			else:
				session.current_track = tracks.first()
			session.save()
			async_to_sync(self.channel_layer.group_send)(
				self.session_name, {"type": "announce.track"}
			)


	def announce(self, event):
		user = event["user"]
		self.send(text_data=json.dumps({"joined": user}))

	def announce_track(self, event):
		self.send(text_data=json.dumps({"track": {}}))


	# Receive message from room group
	def chat_message(self, event):
		message = event["message"]

		print(self.scope["user"])

		# Send message to WebSocket
		self.send(text_data=json.dumps({"message": message}))
