from django.http import HttpResponse, HttpResponseNotAllowed, HttpResponseServerError
from django.shortcuts import render
from django.views.generic.edit import FormView

from teamsnap.views import get_teamsnap_client

from .forms import AccountForm, PlayerFormSet, PreferencesForm
from .models import Player
from .utils import gamechanger


class PreferencesFormView(FormView):
    template_name = "gamechanger/form.html"
    form_class = PreferencesForm
    success_url = "/"

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        if form.data["user"] == str(self.request.user.id):
            form.save()
        return super().form_valid(form)

    def get_initial(self):
        """
        Returns the initial data to use for forms on this view.
        """
        initial = super().get_initial()
        initial["user"] = self.request.user
        initial["email"] = self.request.user.username
        # initial['managed_team_id']

        return initial


class AccountFormView(FormView):
    template_name = "gamechanger/form.html"
    form_class = AccountForm
    success_url = "/"

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        if form.data["user"] == str(self.request.user.id):
            form.save()
        return super().form_valid(form)

    def get_initial(self):
        """
        Returns the initial data to use for forms on this view.
        """
        initial = super().get_initial()
        initial["user"] = self.request.user
        initial["email"] = self.request.user.username
        # initial['managed_team_id']

        return initial


def roster_import(request):
    if request.method == "GET":
        from pyteamsnap.api import Member

        client = get_teamsnap_client(request)
        season_id = request.user.gamechanger_preferences.season_id
        team_id = request.user.gamechanger_preferences.team_id
        teamsnap_team_id = request.user.teamsnap_preferences.managed_team_id
        teamsnap_members = {
            f"{member.data['first_name']} {member.data['last_name']}": member
            for member in Member.search(client, team_id=teamsnap_team_id)
        }

        page = "roster"

        d = gamechanger.scrape_page(season_id, team_id, page)
        roster = d["roster"]
        initial = [
            {
                "gamechanger_name": f"{player['fname']} {player['lname']}",
                "fname": player["fname"],
                "lname": player["lname"],
                "teamsnap_name": "{first_name} {last_name}".format(
                    **teamsnap_members[f"{player['fname']} {player['lname']}"].data
                ),
                "id": player.get("player_id"),
                "teamsnap_member_id": teamsnap_members[
                    f"{player['fname']} {player['lname']}"
                ].data["id"],
            }
            for player in roster
        ]
        formset = PlayerFormSet(initial=initial)
        choices = [
            (
                teamsnap_member.data["id"],
                f"{teamsnap_member.data['first_name']} {teamsnap_member.data['last_name']}",
            )
            for teamsnap_member in teamsnap_members.values()
        ]
        for form in formset:
            form.fields["teamsnap_member_id"].widget.choices = choices
            pass
        return render(
            request,
            "gamechanger/roster.html",
            context={"roster": roster, "formset": formset},
        )
    elif request.POST:
        formset = PlayerFormSet(request.POST)
        if formset.is_valid():
            r = []
            for form in formset:
                data = form.cleaned_data
                data.pop("DELETE")
                data.pop("gamechanger_name")
                data.pop("teamsnap_name")
                obj, did_create = Player.objects.update_or_create(**data)
                obj.save()
                r.append(obj)
            return HttpResponse(status=200)
        else:
            return HttpResponseServerError()

        return HttpResponseServerError()
    else:
        return HttpResponseServerError()


def lineup_submit(request):

    from teamsnap.forms import LineupEntryFormset

    if request.GET:
        return HttpResponseNotAllowed()
    if request.POST:
        formset = LineupEntryFormset(request.POST)
        if formset.is_valid():
            lineup_data = [
                form.cleaned_data
                for form in formset
                if form.cleaned_data.get("label")
                and form.cleaned_data.get("sequence") is not None
            ]
            lineup_data.sort(key=lambda x: x.get("sequence"))
            lineup = []

            for lineup_entry in lineup_data:
                d = {
                    "player_id": lineup_entry["gamechanger_player_id"],
                    "position": lineup_entry["label"],
                }
                if lineup_entry["label"] == "DH":
                    for_whom = [
                        e
                        for e in lineup_data
                        if e["position_only"] and e["label"] != "DR"
                    ][0]
                    d["forwhom"] = for_whom["gamechanger_player_id"]
                    lineup.append(d)
                    if for_whom in lineup:
                        lineup_data.remove(for_whom)
                    if for_whom in lineup_data:
                        lineup_data.remove(for_whom)
                    lineup.append(
                        {
                            "player_id": for_whom["gamechanger_player_id"],
                            "position": for_whom["label"],
                        }
                    )
                elif lineup_entry["label"] != "DR":
                    lineup.append(d)
            r = gamechanger.submit_lineup(request, lineup)
            if r.content == b"OK":
                return HttpResponse(status=200)
            else:
                return HttpResponseServerError()
    return HttpResponseServerError()


def stats(request):
    s = gamechanger.stats(request)
    return render(request, "gamechanger/stats.html", context={"stats": s})
    pass
