from django.shortcuts import render, get_object_or_404
from webgui.settings import APPLICATION_NAME
from stats.models import Channel
from .models import GuildAccessToken
from .forms import ChannelSettingsForm
import datetime

def channel_settings(request, channel_id, token):
	# Check if channel and token exists.
	channel = get_object_or_404(Channel, channel_id=channel_id)
	#settings = get_object(ChannelSettings, channel=channel_id)
	token = get_object_or_404(GuildAccessToken, token="{"+token+"}")

	# Check if token is valid.
	#print(token.created.replace(tzinfo=None))
	print(token.created.replace(tzinfo=None) + datetime.timedelta(hours=-1))
	#print(token.created)
	print(datetime.datetime.now() - datetime.timedelta(minutes=10))
	if token.created.replace(tzinfo=None) + datetime.timedelta(hours=-1) > datetime.datetime.now() - datetime.timedelta(minutes=10):
		token_expired = False
	else:
		token_expired = True

	updated = False
	if request.method == 'POST' and not token_expired:
		print("Token valid")
		form = ChannelSettingsForm(request.POST, instance=channel)
		if form.is_valid():
			form.save()
			updated = True
	else:
		print("Token expired")
		form = ChannelSettingsForm(instance=channel)

	context = {
		'title': 'Channel settings',
		'icon': 'screwdriver',
		'description': 'Modify channel settings for ' + APPLICATION_NAME,
		'keywords': 'settings, channel',
		'form': form,
		'updated': updated,
		'token_expired': token_expired,
	}
	return render(request, 'config/channel_settings.html', context)
