from django.shortcuts import render
from django.views import View
from rest_framework.parsers import FormParser
from rest_framework.views import APIView

from core.lib.manage import threshold
from core.views.manage.permissions import SuperUserRequiredMixin


class ThresholdIRCStats(SuperUserRequiredMixin, View):
    stats_template = "manage/threshold/irc/overview/stats.html"

    def post(self, request):
        stats = threshold.get_irc_stats()
        context = {"stats": stats}
        return render(request, self.stats_template, context)


class ThresholdIRCNetworks(SuperUserRequiredMixin, View):
    template_name = "manage/threshold/irc/overview/networks.html"

    def post(self, request):
        networks = threshold.get_irc_networks()
        context = {"networks": networks}
        return render(request, self.template_name, context)


class ThresholdIRCNetworkInfo(SuperUserRequiredMixin, View):
    template_name = "manage/threshold/irc/network/info.html"

    def post(self, request, net):
        network = threshold.get_irc_network(net)
        context = {"network": network}
        return render(request, self.template_name, context)


class ThresholdIRCNetworkInfoEdit(SuperUserRequiredMixin, APIView):
    template_name = "manage/threshold/irc/network/edit-network.html"
    parser_classes = [FormParser]

    def get(self, request, net):
        """
        Return the form to edit a network.
        """
        network = threshold.get_irc_network(net)
        editable = ["auth", "host", "last", "port", "security"]
        context = {
            "net": net,
            "network": {k: v for k, v in network.items() if k in editable},
        }
        return render(request, self.template_name, context)

    def post(self, request, net):
        """
        Actually edit the network.
        Returns the info pane with a message about the success.
        """
        template_name = "manage/threshold/irc/network/info.html"
        edited = threshold.edit_irc_network(net, request.data)
        if edited["success"]:
            message = "Successfully edited!"
            message_class = "success"
        else:
            if "reason" in edited:
                message = f"Error editing network: {edited['reason']}"
            else:
                message = "Error editing network"
            message_class = "danger"
        network = threshold.get_irc_network(net)
        context = {"network": network, "message": message, "class": message_class}
        return render(request, template_name, context)


class ThresholdIRCNetworkRelays(SuperUserRequiredMixin, View):
    template_name = "manage/threshold/irc/network/relays.html"

    def get(self, request, net):
        relays = threshold.get_irc_relays(net)
        context = {"relays": relays["relays"]}
        return render(request, self.template_name, context)


class ThresholdIRCNetworkRelayStatus(SuperUserRequiredMixin, APIView):
    template_name = "manage/threshold/irc/network/relays.html"

    def get(self, request, net, num, status):
        """
        Change the status of a relay.
        """
        edited = threshold.change_network_status(net, num, status)
        if edited["success"]:
            message = "Successfully completed!"
            message_class = "success"
        else:
            if "reason" in edited:
                message = f"Error updating status: {edited['reason']}"
            else:
                message = "Error updating status"
            message_class = "danger"
        relays = threshold.get_irc_relays(net)
        context = {
            "relays": relays["relays"],
            "message": message,
            "class": message_class,
        }
        return render(request, self.template_name, context)


class ThresholdIRCNetworkChannels(SuperUserRequiredMixin, APIView):
    """
    List the channels a network is on.
    Allow parting and joining new ones.
    Re-render the same template if we join/part to make it simple.
    """

    template_name = "manage/threshold/irc/network/channels.html"
    parser_classes = [FormParser]

    def post(self, request, net):
        """
        Get list of channels for network.
        :param net: network name
        """
        channels = threshold.get_irc_channels(net)
        context = {"net": net, "channels": channels["channels"]}
        return render(request, self.template_name, context)

    def delete(self, request, net, channel):
        """
        Part a channel.
        :param net: network name
        :param channel: channel name
        """
        parted = threshold.part_channel(net, channel)
        if parted:
            message = f"Requested part on relays: {', '.join(parted['relays'])}"
            message_class = "success"
        else:
            message = parted["reason"]
            message_class = "danger"

        channels = threshold.get_irc_channels(net)
        context = {
            "net": net,
            "channels": channels["channels"],
            "message": message,
            "class": message_class,
        }
        return render(request, self.template_name, context)

    def put(self, request, net):
        """
        Join a channel.
        :param net: network name
        """
        if "channel" not in request.data:
            message = "No channel specified"
            message_class = "danger"
        else:
            channel = request.data["channel"]
            print("CHANNEL", channel)
            joined = threshold.join_channel(net, channel)
            print("JOINED", joined)
            if joined:
                message = f"Requested join on relay: {joined['relays']}"
                message_class = "success"
            else:
                message = joined["reason"]
                message_class = "danger"

        channels = threshold.get_irc_channels(net)
        context = {
            "net": net,
            "channels": channels["channels"],
            "message": message,
            "class": message_class,
        }
        return render(request, self.template_name, context)
