from django import forms
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 Account, Player, Preferences, Team
from .utils import gamechanger
from .utils.gamechanger import get_gamechanger_client


def teams(request):
    # season_id = request.user.gamechanger_preferences.season_id
    # team_id = request.user.gamechanger_preferences.team_id
    gamechanger = get_gamechanger_client(request)
    teams = gamechanger.get_teams()
    return render(request, "gamechanger/teams.html", context={"teams": teams})


def events(request):
    gamechanger = get_gamechanger_client(request)
    events = gamechanger.get_events(request)
    return render(request, "gamechanger/events.html", context={"events": events})


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.cleaned_data["user"].username == str(
            self.request.user.gamechanger_account.user
        ):
            form.save()
        return super().form_valid(form)

    def form_invalid(self, form):
        pass

    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 get_form(self):
        """
        Returns the initial data to use for forms on this view.
        """

        try:
            preferences = Preferences.objects.get(user=self.request.user)
            form = PreferencesForm(instance=preferences, **self.get_form_kwargs())

        except Preferences.DoesNotExist:
            form = super().get_form(self.form_class)

        gamechanger = get_gamechanger_client(self.request)
        teams = gamechanger.get_teams()

        team_instances = []
        choices = []
        for team in teams:
            instance, _ = Team.objects.get_or_create(
                id=team["id"],
                slug="-".join(team["team_slug"].split("-")[:-1]),
                season_slug=team["season_slug"],
            )
            team_instances.append(instance)
            choices.append((team["id"], f"{team['name']} ({team['season']})"))

        form.fields["managed_team"].widget = forms.Select(
            choices=choices, attrs={"class": "form-control"}
        )
        # form.fields["managed_team"].choices = [choice[0] for choice in choices]
        # form.fields["managed_team"].widget.choices = choices

        return form


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 get_form(self):
        """
        Returns the initial data to use for forms on this view.
        """

        try:
            contact = Account.objects.get(user=self.request.user)
            form = AccountForm(instance=contact, **self.get_form_kwargs())
        except Account.DoesNotExist:
            form = super().get_form(self.form_class)

        return form


def roster(request):
    gamechanger = get_gamechanger_client(request)
    roster = gamechanger.get_roster()

    return render(request, "gamechanger/roster.html", context={"roster": roster})


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

        gc_client = get_gamechanger_client(request)
        season_slug = request.user.gamechanger_preferences.managed_team.season_slug
        team_slug = request.user.gamechanger_preferences.managed_team.slug
        team_id = request.user.gamechanger_preferences.managed_team.id

        ts_client = get_teamsnap_client(request)
        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(ts_client, team_id=teamsnap_team_id)
        }

        roster = gc_client.get_roster(
            team_id=team_id, team_slug=team_slug, season_slug=season_slug
        )
        initial = [
            {
                "gamechanger_name": f"{player['fname']} {player['lname']}",
                "fname": player["fname"],
                "lname": player["lname"],
                "teamsnap_name": "{first_name} {last_name}".format(
                    **getattr(
                        teamsnap_members.get(f"{player['fname']} {player['lname']}"),
                        "data",
                        {"first_name": "", "last_name": ""},
                    )
                ),
                "id": player.get("player_id"),
                "teamsnap_member_id": getattr(
                    teamsnap_members.get(f"{player['fname']} {player['lname']}"),
                    "data",
                    {"id": None},
                )["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_import.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:
        from gamechanger.utils.gamechanger import get_gamechanger_client

        gc_client = get_gamechanger_client(request)
        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 = gc_client.submit_lineup(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
