# passerelle.contrib.tlmcom
# Copyright (C) 2015  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.views.generic import DetailView
from django.views.generic.base import View
from django.views.generic.detail import SingleObjectMixin
from django.http import HttpResponse, HttpResponseBadRequest

from .models import TlmCom


class TlmComDetailView(DetailView):
    model = TlmCom
    template_name = 'passerelle/contrib/tlmcom/detail.html'


class CallStart(SingleObjectMixin, View):
    event = 'start'
    model = TlmCom

    def get(self, request, *args, **kwargs):
        try:
            caller = request.GET['caller']
            callee = request.GET['callee']
        except KeyError:
            return HttpResponseBadRequest('caller and callee are mandatory')
        username = request.GET.get('id')
        if username:
            # "id" is a tlmcom dirty hack: the real username is just the part after the dot
            username = username.split('.', 1).pop()
        data = dict(request.GET.iteritems())
        for key in ['caller', 'callee', 'id']:
            data.pop(key, None)
        self.get_object().notify_welco(self.event, caller, username or callee, data)
        return HttpResponse('ok')


class CallStop(CallStart):
    event = 'stop'
