from django import forms
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.shortcuts import render, render_to_response
from django.urls import reverse, reverse_lazy
from django.views import generic
from django.views.generic.edit import CreateView, FormView
# Create your views here.
from accounts.forms import CreateCharacterForm
from accounts.models import Accounts, Players, Towns
from accounts.utils import LoginHelper, VocationHelper


class RegisterAccountView(CreateView):
    model = Accounts
    fields = ['name', 'password', 'email']
    template_name = 'register_account.html'

    def get_form(self, form_class=None):
        form = super(RegisterAccountView, self).get_form(form_class)
        form.fields['password'].widget = forms.PasswordInput()
        return form

    def form_valid(self, form):
        self.object = form.save(commit=False)

        # create django user
        u, created = User.objects.get_or_create(
            username=self.object.name,
            email=self.object.email,
        )
        if created:
            u.set_password(self.object.password)
            u.save()
            # create tibia account with sha1 hashed password
            hashed_password = LoginHelper.hash_password(self.object.password)
            self.object.password = hashed_password
            self.object.linked_django_user = u
            self.object.save()
        return render_to_response(self.template_name, self.get_context_data())

class IndexView(generic.ListView):
    template_name = 'index.html'
    context_object_name = 'best_players'

    def get_queryset(self):
        return Players.objects.filter(group_id=1).order_by('-level').values('name', 'level')[:10]

class PlayerView(LoginRequiredMixin, generic.ListView):
    template_name = 'players.html'
    context_object_name = 'players'

    def get_queryset(self):
        players = Players.objects.filter(account__linked_django_user=self.request.user)\
            .values('name', 'level', 'vocation')
        return players

    def get_context_data(self, **kwargs):
        context = super(PlayerView, self).get_context_data(**kwargs)
        players = context['players']
        context['players'] = [{
            'name': p['name'],
            'level': p['level'],
            'vocation': VocationHelper.vocation_to_string(p['vocation'])}
            for p in players]
        return context

class CreateCharView(LoginRequiredMixin, FormView):
    form_class = CreateCharacterForm
    template_name = 'add_character.html'
    success_url = reverse_lazy('accounts:characters')

    def form_valid(self, form):
        rookgaard = Towns.objects.get(name='Rookgaard Tutorial Island')
        start_health = 150
        start_mana = 55
        start_cap = 400
        user = self.request.user
        account = Accounts.objects.get(linked_django_user=user)
        player = Players.objects.create(
            name=form.cleaned_data['name'],
            level=1,
            #vocation=int(form.cleaned_data['vocation']),
            vocation=0,
            sex=int(form.cleaned_data['sex']),
            posx=rookgaard.posx,
            posy=rookgaard.posy,
            posz=rookgaard.posz,
            health=start_health,
            healthmax=start_health,
            mana=start_mana,
            manamax=start_mana,
            cap=start_cap,
            account_id=account.id,
            town_id=rookgaard.id,
        )
        return super(CreateCharView, self).form_valid(form)

