from _ast import In



from django.shortcuts import render

from django.http import JsonResponse

from datetime import datetime





from django.shortcuts import render

from django.http import Http404

from random import randint

from rest_framework import status

from rest_framework.views import APIView

from rest_framework.response import Response

from users.models import User, Interest

from jmspots.models import *

from chatroom.models import *

from rest_framework import status

from users.serializers import UserSerializer, InterestSerializer

from jmspots.serializers import *



from rest_framework.serializers import *

from rest_framework.response import Response

from .models import *

from rest_framework.decorators import api_view

from django.core import serializers

from django.http import HttpResponse

import json

from itertools import chain

from django.db import transaction

from rest_framework.renderers import JSONRenderer

from django.http import JsonResponse

from django.core import serializers

import json

from django.http import HttpResponse

import string

import random

import urllib

import os

import urllib.request

from fcm.utils import get_device_model

MyDevice = get_device_model()

from datetime import datetime

from django.forms import formset_factory
from django.forms import modelformset_factory








class CategorytList(APIView):



    def get(self, request):

        category = Category.objects.all()

        serializer = CategorySerializer(category, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)



    def post(self, request):

        serializer = CategorySerializer(data=request.data)

        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors)




class HorairesList(APIView):



    def get(self, request):

        horaires = Horaires.objects.all()

        serializer = HorairesSerializer(horaires, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)



    def post(self, request):

        serializer = HorairesSerializer(data=request.data)

        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors)







class FavouriteCardList(APIView):



    def get(self, request):

        category = UserCardFavourite.objects.all()

        serializer = UserCardFavouriteSerializer(category, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)



    def post(self, request):

        serializer = UserCardFavouriteSerializer(data=request.data)

        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors)





#

# def get(self, request):

#     #list_card_institutionel = CardShare.objects.filter(events=None)

#     list_card_institutionel = CardShare.objects.all()

#     #list_card_event = CardShare.objects.filter(institution=None)

#     q_json = serializers.serialize("json", list_card_institutionel)

#     return HttpResponse(q_json, content_type='application/json')



class CardList(APIView):



    def get(self, request):

        list_card_institutionel = Card.objects.all()

        #return HttpResponse(json.dumps(list_card_institutionel), content_type='application/json')



        # list_card_institutionel = Card.objects.exclude(event__is_public=False).values_list(

        #     'id', 'institution__id', 'institution', 'event__id', 'event__name', 'event__description', 'event__jm_tag',

        #     'event__created', 'event__is_public', 'event__spot','event__owner',

        #     'category', 'file',

        # )

        serializer = CardSerializer(list_card_institutionel, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)







    def post(self, request):

        serializer = Card(data=request.data)

        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors)









class EventList(APIView):



    def get(self, request):

        event = Event.objects.all()

        serializer = EventSerializer(event, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)





    def post(self, request):

        serializer = EventSerializer(data=request.data)

        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors)











class InstitutionList(APIView):



    def get(self, request):

        institution = Institution.objects.all()

        serializer = InstitutionSerializer(institution, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)





    def post(self, request):

        serializer = InstitutionSerializer(data=request.data)

        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors)







class SpotList(APIView):



    def get(self, request):

        spot = Spot.objects.all()

        serializer = SpotSerializer(spot, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)



    def post(self, request):

        serializer = SpotSerializer(data=request.data)

        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors)







class UserCardList(APIView):



    def get(self, request):

        usercard = UserCard.objects.all()

        serializer = UserCardSerializer(usercard, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)



    def post(self, request):

        serializer = UserCardSerializer(data=request.data)

        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors)







class UserCardFavouriteList(APIView):



    def get(self, request):

        usercardfavourite = UserCardFavourite.objects.all()

        serializer = UserCardFavouriteSerializer(usercardfavourite, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)



    def post(self, request):

        serializer = UserCardFavouriteSerializer(data=request.data)

        if serializer.is_valid():

            serializer.save()

            # res = {"status": 0, "message": "Enregistrement de la carte favorite est bien effectué"}

            # return Response(data=json.dumps(res), status=status.HTTP_201_CREATED)

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors)











@api_view(['POST'])

def listFavourite(request):



    if request.method == "POST":



        senders = request.data['sender']

        try:

            u = UserCardFavourite.objects.get(sender=senders)

            serialiser  = UserCardFavouriteSerializer(u)

            return Response(serialiser.data)

        except:

            return Response(data={'status': -1, 'message': 'Cet utilisateur ne figure pas dans la base de données.'})











@api_view(['GET'])

def get_Cartes_public(request):



    list_card = Card.objects.filter(is_public=True)

    serializer = CardSerializer(list_card, many=True)

    return Response(serializer.data, status=status.HTTP_200_OK)





@api_view(['GET'])

def get_Cartes_event_public(request):

    list_card = Card.objects.filter(is_public=True, institution=None)

    serializer = CardSerializer(list_card, many=True)

    return Response(serializer.data, status=status.HTTP_200_OK)





@api_view(['GET'])

def get_Cartes_institution_public(request):



    list_card = Card.objects.filter(is_public=True, event=None)

    serializer = CardSerializer(list_card, many=True)

    return Response(serializer.data, status=status.HTTP_200_OK)









@api_view(['POST'])

def get_Create_Carte(request):



    id=request.data['id']

    usercard = Card.objects.filter(owner=id)

    serializer = CardSerializer(usercard,  many=True)



    return Response(serializer.data, status=status.HTTP_200_OK)









@api_view(['POST'])



def get_Favourite_Card(request):

    id=request.data['id']

    usercardfavourite = UserCardFavourite.objects.filter(sender=id)

    serializer = UserCardFavouriteSerializer(usercardfavourite,  many=True)

    return Response(serializer.data, status=status.HTTP_200_OK)







#  Bonne

# @api_view(['POST'])

# def get_Create_Carte_Favourite(request):

#

#     id=request.data['id']

#     usercard = Card.objects.filter(owner=id)

#     usercardfavourite = UserCardFavourite.objects.filter(sender=id)

#     result_list = list(chain(usercardfavourite, usercard))

#     data2 = serializers.serialize("json", result_list)

#     return Response(data2)







# @api_view(['POST']) Bonne

# def get_Create_Carte_Favourite(request):

#

#     id=request.data['id']

#     usercard = Card.objects.filter(owner=id).values('owner', 'file')

#     usercardfavourite = UserCardFavourite.objects.filter(sender=id).select_related('sender')

#

#     ## Bonne      result_list = list(chain(usercardfavourite, usercard))

#     ## Bonne 2   result_list = list(usercard)+ list(usercardfavourite)

#     result_list = list(usercard)

#     ### result_list = list(chain(usercardfavourite))

#     # bonne 3 data = serializers.serialize("json", result_list, fields=('owner','institution', 'sender', 'date_created', 'file', 'event', 'category'))

#     data = serializers.serialize("json", result_list,)

#     # return HttpResponse(data, content_type="application/json")

#     return HttpResponse(data, content_type="application/json")

#     ## return JsonResponse(json.dumps(result_list), safe=True)











@api_view(['POST'])

def get_Create_Carte_Favourite(request):



    id=request.data['id']

    usercardfavourite = UserCardFavourite.objects.filter(sender=id)



    if len(usercardfavourite) != 0:

        # serializer = UserCardSerializer(usercard, many=True)

        favourite_serializer = UserCardFavouriteSerializer(usercardfavourite,  many=True)

        res = {"status": 0, "message": "La liste des cartes favorites.", 'data': favourite_serializer.data}



        # favourite_serializer = UserCardFavouriteSerializer(usercardfavourite,  many=True)

        # serializer = card_serializer.data + favourite_serializer.data

        serializer = favourite_serializer.data





        ### return Response(serializer)

        return Response(data=res, content_type='application/json')



    else :

        content = {'status': 1, 'message': 'Pas de carte créée.'}

        return Response(content)











# @api_view(['POST'])

# def get_Create_Carte_Favourite(request):

#

#     id=request.data['id']

#

#     usercard = Card.objects.filter(owner=id)

#     card_serializer = CardSerializer(usercard,  many=True)

#     usercardfavourite = UserCardFavourite.objects.filter(sender=id)

#     favourite_serializer = UserCardFavouriteSerializer(usercardfavourite,  many=True)

#     # favourite_serializer = UserCardFavouriteSerializer(usercardfavourite,  many=True)

#     serializer = card_serializer.data + favourite_serializer.data

#     # serializer = favourite_serializer.data

#     return Response(serializer)











@api_view(['POST'])

def get_Shared_Card(request):



    id=request.data['id']

    usercard = UserCard.objects.filter(users_receivers=id, state='RECEIVED')



    if len(usercard) != 0:

        print (usercard)

        serializer = UserCardSerializer(usercard,  many=True)

        res = {"status": 0, "message": "La liste des cartes partagées.", 'data':serializer.data}



##        return JsonResponse(data=json.dumps(res), content_type='application/json')

        return Response(data=res, content_type='application/json')

        ## return Response(data=json.dumps(res), status=status.HTTP_200_OK)

        ##### return Response(serializer.data, status=status.HTTP_200_OK)

    else:

        content = {'status': 1, 'message': 'Pas de carte partagée.'}

        return Response(content)







@api_view(['POST'])

@transaction.atomic

def usercardShared(request):

    if request.method == "POST":


        sender1 = request.data['sender']
        card = request.data['card']
        list_receivers = request.data['receivers']
        usercard = UserCard()


        # Si l'utilisateur n'a pas de device Token
        device_sender = MyDevice.objects.filter(user_id=sender1).values('reg_id')
        print('Valeur de device sender')
        print(len(device_sender))
        print(device_sender)

        print(' debut sender ')

        if len(device_sender) == 0:
            print(' dans sender ')

            return Response(data={
                'status': -1,
                'message': 'Nous rencontrons un problème reconnectez vous SVP.'
            })

        # Fin du sender

        i = 0

        with transaction.atomic():
            while i < (len(list_receivers)):
                print (list_receivers[i])

                device897 = MyDevice.objects.filter(user_id=list_receivers[i]).values('reg_id', 'is_active')
                print('Valeur de device')
                print(device897)
                print(' voila ')
                print(len(device897))
                # is_active=True,
                print(' valeur de is active')
                # print(device[z]['is_active'])




                if len(device897) == 0:
                    print(' vide ')
                    print(' vide ')
                    print(' vide ')
                    print(' vide ')

                    device111 = MyDevice.objects.filter(user_id=sender1).values('reg_id', 'is_active')

                    device_last111 = MyDevice.objects.get(reg_id=device111[0]['reg_id'])
                    print(device_last111)
                    user1 = User.objects.filter(id=list_receivers[i]).values('first_name', 'last_name')
                    print(user1)
                    print(' Envoie ')
                    print(' Personne ')
                    print(str(user1[0]['first_name']))
                    print(str(user1[0]['last_name']))
                    # device_last.send_message({'message': 'my test message'}, collapse_key='something')

                    # device_last.send_message(data={"title":"Nouveau Invitation",
                    #                                "sender":str(user1[0]['first_name'])+" "+str(user1[0]['last_name']),
                    #                                "type":0,
                    #                                "latitude": latitude,
                    #                                "longitude": longitude
                    #                                })

                    # }

                    cardsss1 = Card.objects.filter(id=card).values('file',
                                                                   'event__spot__id',
                                                                   'institution__spot__id',
                                                                   'event__spot__latitude',
                                                                   'event__spot__longitude',
                                                                   'institution__spot__latitude',
                                                                   'institution__spot__longitude',
                                                                   'event__name',
                                                                   'institution__name')
                    print(cardsss1)

                    if cardsss1[0]['event__spot__id'] == None:
                        print(' Carte institutionnelles ')

                        device_last111.send_message(data={"title": "Echec de l'envoi",
                                                          "receivers": str(user1[0]['first_name']) + " " + str(user1[0]['last_name']),
                                                          "type": 12,
                                                          "message": "n'a pas reçu le partage de la carte "+str(cardsss1[0]['institution__name']),
                                                          "name": str(cardsss1[0]['institution__name']),
                                                          "file": str('/media/') + str(cardsss1[0]['file'])
                                                          })
                        i += 1

                    else:

                        print(' Carte Evenementielles ')

                        print('Notification non envoyé du fcm')
                        device_last111.send_message(data={"title": "Echec de l'envoi",
                                                          "receivers": str(user1[0]['first_name']) + " " + str(user1[0]['last_name']),
                                                          "type": 12,
                                                          "message": "n'a pas reçu le partage de la carte "+ str(cardsss1[0]['event__name']),
                                                          "name": str(cardsss1[0]['event__name']),
                                                          "file": str('/media/') + str(cardsss1[0]['file'])
                                                          })

                        i+=1
                else:

                    senders = User.objects.get(id=sender1)
                    usercard.sender = senders
                    print (usercard.sender)
                    print (' cc 1 ')

                    cards = Card.objects.get(id=card)
                    usercard.card = cards
                    print (usercard.card)
                    print (' cc 2 ')





                    print (list_receivers)
                    u = User.objects.get(id=list_receivers[i])
                    usercard.users_receivers = u
                    print (usercard.users_receivers)



                    print (' cc 3 ')

                    a = UserCard(
                        sender = senders,
                        card = cards,
                        users_receivers = u
                    )

                    a.save()

                    # usercard.save()

                    print (' LA VALEUR DE A ')
                    print (' ID de la carte du Partage *********** ')
                    last_requete = UserCard.objects.latest('id')
                    print (' ID de la carte du Partage *********** 2222 ')
                    last_reque = last_requete.pk
                    print (last_reque)

                    print(' Debut de la notification ')
                    print(' Debut de la notification ')
                    print(' Debut de la notification ')
                    print(' Debut de la notification ')



                    device = MyDevice.objects.filter(user_id=list_receivers[i]).values('reg_id')
                    print('Valeur de device')
                    print(device)





                    if len(device) == 0:
                        print(' vide ')
                        print(' vide ')
                        print(' vide ')
                        print(' vide ')

                        device1122 = MyDevice.objects.filter(user_id=sender1).values('reg_id', 'is_active')

                        device_last1122 = MyDevice.objects.get(reg_id=device1122[0]['reg_id'])
                        print(device_last111)
                        user1 = User.objects.filter(id=list_receivers[i]).values('first_name', 'last_name')
                        print(user1)
                        print(' Envoie ')
                        print(' Personne ')
                        print(str(user1[0]['first_name']))
                        print(str(user1[0]['last_name']))
                        # device_last.send_message({'message': 'my test message'}, collapse_key='something')

                        # device_last.send_message(data={"title":"Nouveau Invitation",
                        #                                "sender":str(user1[0]['first_name'])+" "+str(user1[0]['last_name']),
                        #                                "type":0,
                        #                                "latitude": latitude,
                        #                                "longitude": longitude
                        #                                })

                        # }

                        cardsss1 = Card.objects.filter(id=card).values('file',
                                                                       'event__spot__id',
                                                                       'institution__spot__id',
                                                                       'event__spot__latitude',
                                                                       'event__spot__longitude',
                                                                       'institution__spot__latitude',
                                                                       'institution__spot__longitude',
                                                                       'event__name',
                                                                       'institution__name')
                        print(cardsss1)

                        if cardsss1[0]['event__spot__id'] == None:
                            print(' Carte institutionnelles ')

                            device_last1122.send_message(data={"title": "Echec de l'envoi",
                                                              "receivers": str(user1[0]['first_name']) + " " + str(
                                                                  user1[0]['last_name']),
                                                              "type": 12,
                                                              "message": "n'a pas reçu le partage de la carte " + str(
                                                                  cardsss1[0]['event__name']),
                                                              "name": str(cardsss1[0]['event__name']),
                                                              "file": str('/media/') + str(cardsss1[0]['file'])
                                                              })
                            i += 1

                        else:

                            print(' Carte Evenementielles ')

                            print('Notification non envoyé du fcm')
                            device_last1122.send_message(data={"title": "Echec de l'envoi",
                                                              "receivers": str(user1[0]['first_name']) + " " + str(
                                                                  user1[0]['last_name']),
                                                              "type": 12,
                                                              "message": "n'a pas reçu le partage de la carte " + str(
                                                                  cardsss1[0]['event__name']),
                                                              "name": str(cardsss1[0]['event__name']),
                                                              "file": str('/media/') + str(cardsss1[0]['file'])
                                                              })

                            i += 1


                    else:

                        device1 = device[0]['reg_id']
                        print(device1)
                        print(' Dans la boucle 2')

                        device_last = MyDevice.objects.get(reg_id=device[0]['reg_id'])
                        print(device_last)
                        user1 = User.objects.filter(id=sender1).values('first_name', 'last_name')
                        print(user1)

                        print(' Envoie ')

                        cardsss = Card.objects.filter(id=card).values('file',
                                                                      'event__spot__id',
                                                                      'institution__spot__id',
                                                                      'event__spot__latitude',
                                                                      'event__spot__longitude',
                                                                      'institution__spot__latitude',
                                                                      'institution__spot__longitude',
                                                                      'event__name',
                                                                      'institution__name')
                        print(cardsss)

                        # device_last.send_message({'message': 'my test message'}, collapse_key='something')

                        #
                        # device_last.send_message({"title": "Nouvelle Invitation",
                        #                           "body": str(user1[0]['first_name']) + " " + str(
                        #                               user1[0]['last_name']) + "Vous invite à le rejoindre à",
                        #                           "file": str(cardsss[0]['file'])})


                        if cardsss[0]['event__spot__id'] == None:
                            print(' Carte institutionnelles ')

                            device_last.send_message(data={"title": "Nouvelle invitation",
                                                           "sender": str(user1[0]['first_name']) + " " + str(
                                                               user1[0]['last_name']),
                                                           "file": str('/media/') + str(cardsss[0]['file']),
                                                           "latitude": cardsss[0]['institution__spot__latitude'],
                                                           "longitude": cardsss[0]['institution__spot__longitude'],
                                                           "name": str(cardsss[0]['institution__name']),
                                                           "type": 2,
                                                           "id_requette": last_reque
                                                           })
                            i += 1

                        else:

                            print(' Carte Evenementielles ')
                            device_last.send_message(data={"title": "Nouvelle invitation",
                                                           "sender": str(user1[0]['first_name']) + " " + str(
                                                               user1[0]['last_name']),
                                                           "file": str('/media/') + str(cardsss[0]['file']),
                                                           "latitude": cardsss[0]['event__spot__latitude'],
                                                           "longitude": cardsss[0]['event__spot__longitude'],
                                                           "name": str(cardsss[0]['event__name']),
                                                           "type": 2,
                                                           "id_requette": last_reque
                                                           })

                            i+=1






        return Response(data={

            'status': 0,
            'message': 'Le partage de la carte s\'est bien effectué.'
        })







@api_view(['POST'])

def usercardShared_last(request):



    if request.method == 'POST':



        id = request.data['id']

        try:



            usercard = UserCard.objects.filter(sender=id, is_active=False).last()

            serializer = UserCardSerializer(usercard)

            return Response(serializer.data, status=status.HTTP_200_OK)



        except:

            return Response(

                data={

                    'status': 1,

                    'message': 'Utilisateur inexistant.'})









@api_view(['POST'])

def change_is_active_usercard(request):



    if request.method == 'POST':



        id = request.data['id']



        usercard = UserCard.objects.get(id=id)



        usercard.is_active = True

        usercard.save()

        return Response(

            data={

                'status': 0,

                'message': 'La modification s\'est effectuée avec succès.'})



    else:

        return Response(

            data={

                'status': 1,

                'message': 'Echec de la modification.'})









@api_view(['POST'])

def acept_decliner_usercard(request):



    if request.method == 'POST':



        id = request.data['id']

        value = request.data['val']



        usercard = UserCard.objects.get(id=id)



        if value == 1:



            usercards = UserCard.objects.filter(id=id).values('card__id',
                                                              'card__file',
                                                              'state',
                                                              'card__owner__first_name',
                                                              'card__owner__last_name',
                                                              'card__owner__photo',
                                                              'card__institution__name',
                                                              'card__institution__spot__name',
                                                              'card__institution__spot__latitude',
                                                              'card__institution__spot__longitude',
                                                              'card__event__name',
                                                              'card__event__description',
                                                              'card__event__spot__name',
                                                              'card__event__spot__latitude',
                                                              'card__event__spot__longitude',
                                                              'card__event__date_begin',
                                                              'card__event__date_end',
                                                              'card__event__chatroom__content',
                                                              'card__event__chatroom__id',
                                                              'card__event__chatroom__userss__first_name',
                                                              'card__event__chatroom__userss__last_name',
                                                              'card__event__chatroom__userss__photo' ,
                                                              'id',
                                                              'users_receivers',
                                                              'sender',
                                                              'sender__first_name',
                                                              'sender__last_name',
                                                              'sender__photo')

            if usercards[0]['card__event__chatroom__id'] != None:

                usercard.state = 'RECEIVED'

                usercard.save()

                chats = ChatGroup.objects.get(id=usercards[0]['card__event__chatroom__id'])
                userss = User.objects.get(id=usercards[0]['users_receivers'])

                chats.users.add(userss)
                chats.save()





                device3 = MyDevice.objects.filter(user_id=userss).values('reg_id')
                print(device3)


                device = MyDevice.objects.filter(user_id=userss).values('reg_id')
                print('Valeur de device')
                print(device)

                device1 = device[0]['reg_id']
                print(device1)
                print(' Dans la boucle 2')

                device_last = MyDevice.objects.get(reg_id=device[0]['reg_id'])
                print(device_last)

                device_last.send_message(data={
                    "sender": str(usercards[0]['sender__first_name']) + " " + str(usercards[0]['sender__last_name']),
                    "title": "Nouveau groupe",
                    "type": 3,
                    "name_groupe": str(usercards[0]['card__event__chatroom__content'])
                })

                usercardsss12 = UserCard.objects.filter(id=id).values('card__id',
                                                                      'card__file',
                                                                      'state',
                                                                      'card__owner__first_name',
                                                                      'card__owner__last_name',
                                                                      'card__owner__photo',
                                                                      'card__institution__name',
                                                                      'card__institution__spot__name',
                                                                      'card__institution__spot__latitude',
                                                                      'card__institution__spot__longitude',
                                                                      'id',
                                                                      'card__event__name',
                                                                      'card__event__description',
                                                                      'card__event__spot__name',
                                                                      'card__event__spot__latitude',
                                                                      'card__event__spot__longitude',
                                                                      'users_receivers',
                                                                      'users_receivers__first_name',
                                                                      'users_receivers__last_name',
                                                                      'users_receivers__photo',
                                                                      'sender',
                                                                      'sender__first_name',
                                                                      'sender__last_name',
                                                                      'sender__photo')

                usersssss = User.objects.get(id=usercards[0]['sender'])

                device23 = MyDevice.objects.filter(user_id=usersssss).values('reg_id')
                print(device23)

                device34 = MyDevice.objects.filter(user_id=usersssss).values('reg_id')
                print('Valeur de device')
                print(device34)

                device12 = device34[0]['reg_id']
                print(device12)
                print(' Dans la boucle 2')

                device_last = MyDevice.objects.get(reg_id=device34[0]['reg_id'])
                print(device_last)

                device_last.send_message(data={
                    "receivers": str(usercardsss12[0]['users_receivers__first_name']) + " " + str(
                        usercardsss12[0]['users_receivers__last_name']),
                    "sender": str(usercardsss12[0]['sender__first_name']) + " " + str(usercardsss12[0]['sender__last_name']),
                    "title": "Acceptez-vous l’invitation ?",
                    "type": 7,
                    "message": "a accepté le partage",
                    "name_card": str(usercardsss12[0]['card__event__name']),
                    "file": str('/media/')+str(usercardsss12[0]['card__file']),
                })



                return Response(
                    data={
                        'status': 0,
                        'message': 'Acceptation de l’invitation effective.'})



            else:
                usercard.state = 'RECEIVED'

                usercard.save()

                usercards = UserCard.objects.filter(id=id).values('card__id',
                                                                  'card__file',
                                                                  'state',
                                                                  'card__owner__first_name',
                                                                  'card__owner__last_name',
                                                                  'card__owner__photo',
                                                                  'card__institution__name',
                                                                  'card__institution__spot__name',
                                                                  'card__institution__spot__latitude',
                                                                  'card__institution__spot__longitude',
                                                                  'id',
                                                                  'users_receivers',
                                                                  'users_receivers__first_name',
                                                                  'users_receivers__last_name',
                                                                  'users_receivers__photo',
                                                                  'sender',
                                                                  'sender__first_name',
                                                                  'sender__last_name',
                                                                  'sender__photo')


                userss = User.objects.get(id=usercards[0]['sender'])



                device3 = MyDevice.objects.filter(user_id=userss).values('reg_id')
                print(device3)

                device = MyDevice.objects.filter(user_id=userss).values('reg_id')
                print('Valeur de device')
                print(device)

                device1 = device[0]['reg_id']
                print(device1)
                print(' Dans la boucle 2')

                device_last = MyDevice.objects.get(reg_id=device[0]['reg_id'])
                print(device_last)

                device_last.send_message(data={
                    "receivers": str(usercards[0]['users_receivers__first_name']) + " " + str(usercards[0]['users_receivers__last_name']),
                    "sender": str(usercards[0]['sender__first_name']) + " " + str(usercards[0]['sender__last_name']),
                    "title": "Acceptez-vous l’invitation ?",
                    "type": 7,
                    "message": "a accepté le partage",
                    "name_card": str(usercards[0]['card__institution__name']),
                    "file": str('/media/')+str(usercards[0]['card__file']),
                })

                return Response(

                    data={

                        'status': 0,

                        'message': 'Acceptation de l’invitation effective.'})



        elif value == 0:

            usercard.state = 'DECLINED'

            usercard.save()

            usercards = UserCard.objects.filter(id=id).values('card__id',
                                                              'card__file',
                                                              'state',
                                                              'card__owner__first_name',
                                                              'card__owner__last_name',
                                                              'card__owner__photo',
                                                              'card__institution__name',
                                                              'card__institution__spot__name',
                                                              'card__institution__spot__latitude',
                                                              'card__institution__spot__longitude',
                                                              'card__event__name',
                                                              'card__event__description',
                                                              'card__event__spot__name',
                                                              'card__event__spot__latitude',
                                                              'card__event__spot__longitude',
                                                              'card__event__date_begin',
                                                              'card__event__date_end',
                                                              'card__event__chatroom__content',
                                                              'card__event__chatroom__id',
                                                              'card__event__chatroom__userss__first_name',
                                                              'card__event__chatroom__userss__last_name',
                                                              'card__event__chatroom__userss__photo',
                                                              'id',
                                                              'users_receivers',
                                                              'users_receivers__first_name',
                                                              'users_receivers__last_name',
                                                              'sender',
                                                              'sender__first_name',
                                                              'sender__last_name',
                                                              'sender__photo')

            userss = User.objects.get(id=usercards[0]['sender'])

            device3 = MyDevice.objects.filter(user_id=userss).values('reg_id')
            print(device3)

            device = MyDevice.objects.filter(user_id=userss).values('reg_id')
            print('Valeur de device')
            print(device)

            device1 = device[0]['reg_id']
            print(device1)
            print(' Dans la boucle 2')

            device_last = MyDevice.objects.get(reg_id=device[0]['reg_id'])
            print(device_last)

            if usercards[0]['card__event__chatroom__id'] != None:

                device_last.send_message(data={
                    "receivers": str(usercards[0]['users_receivers__first_name']) + " " + str(
                        usercards[0]['users_receivers__last_name']),
                    "sender": str(usercards[0]['sender__first_name']) + " " + str(usercards[0]['sender__last_name']),
                    "title": "Déclinez-vous l'invitation ?",
                    "type": 7,
                    "message": "a décliné le partage",
                    "name_card": str(usercards[0]['card__event__name']),
                    "file": str('/media/') + str(usercards[0]['card__file'])

                })

                return Response(

                    data={

                        'status': 0,

                        'message': 'Déclinaison de l’invitation effective.'})

            else:

                device_last.send_message(data={
                    "receivers": str(usercards[0]['users_receivers__first_name']) + " " + str(
                        usercards[0]['users_receivers__last_name']),
                    "sender": str(usercards[0]['sender__first_name']) + " " + str(usercards[0]['sender__last_name']),
                    "title": "Déclinez-vous l'invitation ?",
                    "type": 7,
                    "message": "a décliné le partage",
                    "name_card": str(usercards[0]['card__institution__name']),
                    "file": str('/media/') + str(usercards[0]['card__file'])

                })

                return Response(

                    data={

                        'status': 0,

                        'message': 'Déclinaison de l’invitation effective.'})



        else:

            return Response(

                data={

                    'status': 1,

                    'message': 'Echec de l\'invitation.'})







@api_view(['POST'])

def delete_events(request):



    if request.method == 'POST':



        id = request.data['id']



        return Response(

                data={

                    'status': 1,

                    'message': 'Echec de la modification'})















#  anciennne code



# @api_view(['POST'])

# def suggestion_card(request):

#

#     if request.method == 'POST':

#

#

#         id = request.data['id']

#         dictss = ("Autres", "Sportifs","Site touristique", "Site sportif", "Site de loisir", "Restaurant",

# 	                "Religieux", "Professionnels", "Musicaux", "Mode", "Manifestations", "Ludiques", "Institution académique",

# 	                "Hotel", "Hopital", "Festifs", "Entreprise", "Culinaires", "Commerce", "Cinématographiques", "Centre culturel",

# 	                "Administration", "Académique")

#

#

#

#         interests = User.objects.filter(id=id).values('interest__name')

#         taille = len(interests)

#

#         print (taille)

#         print (interests)

#

#         tableau = []

#         if interests[0]['interest__name'] == None:

#

#             card = Card.objects.filter(is_public=True)

#             serializer = CardSerializer(card, many=True)

#             return Response(serializer.data, status=status.HTTP_200_OK)

#

#         else:

#

#

#             print (' *********** Boucle 2 *********  ')

#             i = 0

#             while i < len(interests):

#                 print (interests[i])

#                 # card = Card.objects.filter(is_public=True).filter(category__name=interests[i])

#                 print (' AAAAAAAAAAA ')

#                 print (dictss[i])

#                 print (' AAAAAAAAAAA ')

#                 j = 0

#                 while j < len(dictss):

#                     print (dictss[j])

#

#                     card = Card.objects.filter(is_public=True).filter(category__name=dictss[j])

#                     tableau.append(card)

#                     print (' Tableau 1')

#                     print (tableau)

#                     print (' Tableau 2 ')

#                     serializer = CardSerializer(tableau[j], many=True)

#

#                     j+=1

#

#                 i+=1

#                 print (' DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD ')

#                 print (serializer.data)

#                 # return Response(serializer.data)

#                 return Response('xvxcvcv')

#

#             #     serializer = CardSerializer(tableau, many=True)

#             #

#             # print (' Tab **********')

#             #

#             # j = 0

#             # while j < len(tableau):

#             #     print (' Boucle J ')

#             #     print (tableau[j])

#             #     serializer = CardSerializer(tableau[j], many=True)

#             #     j += 1

#             # return Response(serializer.data)









@api_view(['POST'])

def addFavoriteCard(request):



    if request.method == "POST":



        try:

            sender = request.data['sender']

            card = request.data['card']

            print (card)



            usercardFavouritesss = UserCardFavourite()



            id_user = User.objects.get(id=sender)

            usercardFavouritesss.sender = id_user

            print (id_user)

            # print (usercardFavouritesss.id_user)


            us = UserCardFavourite.objects.filter(sender=sender, card__in=card).count()
            print (' SENDER ')
            print (us)



            if us > 0:

                return Response(
                    data={
                        'status': -1,
                        'message': 'Cette carte est déjà dans vos favoris.',
                        # 'favourite': favouriteContacts.userss
                    })


            else:



                i = 0

                print(' debut boucle ')



                while i < (len(card)):

                    print (' Boucle ')

                    print (card[i])

                    usercardFavouritesss.save()

                    usercardFavouritesss.card.add(card[i])

                    # favouriteContacts.users.add(listeContact[i])

                    i += 1

                    print (' fin boucle ')



            # favouriteContacts.save()



                return Response(

                    data={

                        'status': 0,

                        'message': 'Enregistrement de la carte favorite effective.',

                        # 'favourite': favouriteContacts.userss

                    })



        except:

            return Response(data={'status': 1, 'message': 'Echec de l\'enregistrement de la carte favorite.'})





# La bonne au dessus

@api_view(['POST'])

def addFavoriteCard2(request):



    if request.method == "POST":



        try:

            sender = request.data['sender']

            card = request.data['card']

            print (card)



            usercardFavouritesss = UserCardFavourite()



            id_user = User.objects.get(id=sender)

            usercardFavouritesss.sender = id_user

            print (id_user)

            # print (usercardFavouritesss.id_user)

            print(' Cool ')
            us = UserCardFavourite.objects.filter(sender=sender, card=card).count()
            print (' SENDER ')
            print (us)



            if us > 0:

                return Response(
                    data={
                        'status': -1,
                        'message': 'Cette carte est déjà dans vos favoris.',
                        # 'favourite': favouriteContacts.userss
                    })


            else:
                print('else')
                usercardFavouritesss.save()

                usercardFavouritesss.card.add(card)


            # favouriteContacts.save()



            return Response(

                data={
                    'status': 0,
                    'message': 'Enregistrement de la carte favorite effective.',

                    # 'favourite': favouriteContacts.userss

                })



        except:

            return Response(data={'status': 1, 'message': 'Echec de l\'enregistrement de la carte favorite.'})











@api_view(['POST'])

def suggestion_card(request):



    if request.method == 'POST':





        id = request.data['id']



        dictss = ("Autres", "Sportifs","Site touristique", "Site sportif", "Site de loisir", "Restaurant",

	                "Religieux", "Professionnels", "Musicaux", "Mode", "Manifestations", "Ludiques", "Institution académique",

	                "Hotel", "Hopital", "Festifs", "Entreprise", "Culinaires", "Commerce", "Cinématographiques", "Centre culturel",

	                "Administration", "Académique")



        # dicts = {"Voiture": {"Sportifs", "Autres"},

        #         "Sport":{"Site touristique"},

        #         "Politique":{"Site sportif"},

        #         "Photographie":{"Site de loisir"},

        #         "People":{"Restaurant"},

        #         "Mode":{"Religieux"},

        #         "Mariage":{"Professionnels"},

        #         "Fêtes":{"Musicaux"},

        #         "Décoration":{"Mode"},

        #         "Culture":{"Manifestations", "Centre culturel"},

        #         "Coiffure":{"Ludiques"},

        #         "Citation":{"Institution"},

        #         "Bricolage":{"académique"},

        #         "Boissons":{"Hotel", "Académique"},

        #         "Art":{"Hopital", "Administration"},

        #         "Architecture":{"Festifs", "Cinématographiques"},

        #         "Animaux":{"Entreprise"},

        #         "Actualite":{"Culinaires", "Commerce"},

        #

        #        }







        dicts = {"Voiture": ["Sportifs"],

                "Sport":["Site touristique"],

                "Politique":["Site sportif"],

                "Photographie":["Site de loisir"],

                "People":["Restaurant"],

                "Mode":["Religieux"],

                "Mariage":["Professionnels"],

                "Fêtes":["Musicaux"],

                "Décoration":["Mode"],

                "Culture":["Manifestations"],

                "Coiffure":["Ludiques"],

                "Citation":["Institution"],

                "Bricolage":["académique"],

                "Boissons":["Hotel"],

                "Art":["Hopital"],

                "Architecture":["Festifs"],

                "Animaux":["Entreprise"],

                "Actualite":["Culinaires"],



               }











        # Petit test

        # values = dicts.values()

        # print (keys)

        # print (values)



        # print (dicts)

        # for cle, valeur in dicts.items():

        #     print(cle, valeur)







        interests = User.objects.filter(id=id).values('interest__name')

        taille = len(interests)



        print (taille)

        print (interests)



        print ('eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee')

        keys = dicts.keys()

        tableau = []

        for x in dicts.keys():

           i = 0

           # while i < len(interests):

           while i < len(interests)-1:



                if x == interests[i]['interest__name']:

                    print (x)

                    print (dicts[x])



                    if len (dicts[x]) == 1:

                        print (dicts[x][0])

                        print (' Taille 1 **********')

                        card = Card.objects.filter(is_public=True).filter(category__name=dicts[x][0])

                        if card.count() != 0:

                            # serializer = CardSerializer(card)

                            # serializer = CardSerializer(card, many=True)

                            tableau.append(card)

                            print (' Tableau ************ ')

                            # print (tableau)





                    # A décommenter

                    # else:

                    #     print ('Taille 2 ***********')

                    #     print (dicts[x])





                    # j = 0

                    # while j < len(dicts[x]):

                    #     print (' PAPAPAPA 1 ')

                    #     print(dicts[j])

                    #     print (' PAPAPAPA 2 ')

                    #     j += 1



                    print (' Taille ')

                    print (len(dicts[x]))

                i+=1



    print (' TABLEAU 1')

    print (tableau)

    print (' TABLEAU 2')



    print (' tableau xxxxxxxxxxxxx ')

    print (list(tableau))

    print (' tableau list tableau fin  ')



    # #### print (list(tableau[0]))

    ##### print (tableau[0])

    print (' tableau tableau 0 ')



    if len(list(tableau))!=0:



        print (' OK ')

        serializer = CardSerializer(list(tableau[0]), many=True)

        print (' tableau xxxxxxxxxxxxx  111111111')



        print (serializer.data)

        return Response(serializer.data)

    else:

        # return HttpResponse(' Aucun information trouvé ')

        card = Card.objects.filter(is_public=True)

        serializer = CardSerializer(card, many=True)

        print (serializer.data)

        return Response(serializer.data)



    # FIn





   ### print (json.dumps(tableau, indent=4, sort_keys=True))



   #  # A voir 1

   #  data = serializers.serialize('json', tableau)

   #  print ('data ******** ')

   # #  print (data)

   #  o = data.strip("[]")

   #  print (' OOOOOOOOOO ')

   #  return HttpResponse(0, mimetype="application/json")

   #  # return JsonResponse({"models_to_return": tableau[0]})

   #  return HttpResponse(0, mimetype="application/json")

   #

   #  # A voir 2

   #

   #

   #

   #  serializer = CardSerializer(tableau)

   #  print (serializer)

   #  # serializer = CardSerializer(list(tableau))

   #  # data = serializers.serialize("json", tableau)

   #  return Response(' cc ')

   #  print (list(tableau))

   #  print (' MANEEE  ')

   #  serializer = CardSerializer(list(tableau), many=True)

   #  return HttpResponse(json.dumps(tableau), content_type="application/json")

   #

   #  return JsonResponse({"models_to_return": list(queryset)})

   #

   #

   #



    # return Response(data.data)

    # return Response(data.data)



    #return Response(serializer.data, status=status.HTTP_200_OK)

    # serializer = CardSerializer(list(tableau), many=True)

    # return Response(serializer.data, status=status.HTTP_200_OK)



        # tableau = []

        # if interests[0]['interest__name'] == None:

        #

        #     card = Card.objects.filter(is_public=True)

        #     serializer = CardSerializer(card, many=True)

        #     return Response(serializer.data, status=status.HTTP_200_OK)

        #

        # else:

        #

        #

        #     print (' *********** Boucle 2 *********  ')

        #     i = 0

        #     while i < len(interests):

        #         print (interests)

        #         print (interests[i])

        #         # card = Card.objects.filter(is_public=True).filter(category__name=interests[i])

        #         print (' AAAAAAAAAAA ')

        #         print (dictss[i])

        #         print (' AAAAAAAAAAA ')

        #         j = 0

        #         while j < len(dictss):

        #             print (dictss[j])

        #

        #             #card = Card.objects.filter(is_public=True).filter(category__name=dictss[j]).filter(owner=id)

        #             card = Card.objects.filter(is_public=True).filter(category__name='Administration').filter(owner=id)

        #             tableau.append(card)

        #             print (' Tableau 1')

        #             print (tableau)

        #             print (' Tableau 2 ')

        #             serializer = CardSerializer(tableau[j], many=True)

        #

        #             j+=1

        #

        #         i+=1

        #         print (' DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD ')

        #         print (serializer.data)

        #         return Response(serializer.data)

        #         # return Response('xvxcvcv')

        #

        #     #     serializer = CardSerializer(tableau, many=True)

        #     #

        #     # print (' Tab **********')

        #     #

        #     # j = 0

        #     # while j < len(tableau):

        #     #     print (' Boucle J ')

        #     #     print (tableau[j])

        #     #     serializer = CardSerializer(tableau[j], many=True)

        #     #     j += 1

        #     # return Response(serializer.data)





 # raise TypeError(repr(o) + " is not JSON serializable")

 # TypeError: <QuerySet [<Card: Qualshore>, <Card: None>]> is not JSON serializable





















# La bonne

#

# @api_view(['POST'])

# def addFavoriteCard(request):

#

#     if request.method == "POST":

#

#         try:

#             sender = request.data['sender']

#             card = request.data['card']

#             print (card)

#

#             usercardFavouritesss = UserCardFavourite()

#

#             id_user = User.objects.get(id=sender)

#             usercardFavouritesss.sender = id_user

#             print (id_user)

#             # print (usercardFavouritesss.id_user)

#

#             i = 0

#             print(' debut boucle ')

#

#             while i < (len(card)):

#                 print (' Boucle ')

#                 print (card[i])

#                 usercardFavouritesss.save()

#                 usercardFavouritesss.card.add(card[i])

#                 # favouriteContacts.users.add(listeContact[i])

#                 i += 1

#                 print (' fin boucle ')

#

#             # favouriteContacts.save()

#

#             return Response(

#                 data={

#                     'status': 0,

#                     'message': 'Enregistrement effectué avec success ',

#                     # 'favourite': favouriteContacts.userss

#                 })

#

#         except:

#             return Response(data={'status': 1, 'message': 'Echec de l\'enregistrement'})

















def create_event(request):

    us = request.session.get('id')

    user = User.objects.get(id=us)



    request.session['first_name'] = user.first_name

    request.session['last_name'] = user.last_name

    request.session['id'] = user.id

    request.session['telephone'] = user.telephone

    cards = Card.objects.filter(owner=user)

    print (cards)

    if cards.count() > 0:

        page = '#page'

        # return render(request, 'dashboard.html', locals())

        return render(request, 'office/events/evenements.html', locals())



    page = '#page'

    return  render(request,'office/events/evenements.html', locals())





















def create_institution(request):

    us = request.session.get('id')

    user = User.objects.get(id=us)



    request.session['first_name'] = user.first_name

    request.session['last_name'] = user.last_name

    request.session['id'] = user.id

    request.session['telephone'] = user.telephone

    cards = Card.objects.filter(owner=user)

    print (cards)

    if cards.count() > 0:

        page = '#page'

        # return render(request, 'dashboard.html', locals())

        return  render(request,'office/institutions/institutions.html', locals())



    page = '#page'

    return  render(request,'office/institutions/institutions.html', locals())









# def new_instutition(request):

## A enlever

# A enlever définitivement

# def new_card(request):

#

#     us = request.session.get('id')

#     user = User.objects.get(id=us)

#

#     if request.method == "POST":

#

#         form = InstitutionForm(request.POST, request.FILES)

#

#         if form.is_valid():

#             institution = Institution()

#             spot = Spot()

#             institution.name= form.cleaned_data["name"]

#             institution.description = form.cleaned_data["description"]

#             institution.spot = form.cleaned_data["spot"]

#             institution.save()

#

#             return render(request, 'dashboard.html')

#     else:

#         form = InstitutionForm()

#     return render(request, 'office/institutions/import.html',locals())







# def new_card(request):

def new_instutition(request):



    us = request.session.get('id')

    user = User.objects.get(id=us)



    request.session['first_name'] = user.first_name

    request.session['last_name'] = user.last_name

    request.session['id'] = user.id

    request.session['telephone'] = user.telephone

    cards = Card.objects.filter(owner=user)

    print (cards)

    # if cards.count() > 0:

    #     page = '#page'

    #     return render(request, 'dashboard.html', locals())

    # page = 'page'



    if request.method == "POST":



        form = CardForm(request.POST or None, request.FILES or None)

        forminstitution = InstitutionForm(request.POST or None, request.FILES or None)

        spotform = SpotForm(request.POST or None, request.FILES or None)

        # horairesform = HorairesForm(request.POST or None, request.FILES or None)



        print (' AVANT ')
        # print (horairesform)

        # if form.is_valid() and forminstitution.is_valid() and spotform.is_valid() and horairesform.is_valid():
        if form.is_valid() and forminstitution.is_valid() and spotform.is_valid():



            spot = Spot()

            institution = Institution()

            card = Card()

            horaires = Horaires()

            print(' Dnas ')
            cards = Card.objects.filter(jm_tag=str('jm_')+form.cleaned_data["jm_tag"])
            print (cards)
            #if (len(cards))==0:

            #    print ('COOL ')
            #else:
            #    print ('NON COOL ')




            if (len(cards)) == 0:
                print ('COOL ')
            else:
                message = "Ce « JM_Tag » existe déjà."
                return render(request, 'office/institutions/import.html', locals())
            #print (' FIN ')




            spot.name = forminstitution.cleaned_data["name"]

            spot.latitude = spotform.cleaned_data["latitude"]

            spot.longitude = spotform.cleaned_data["longitude"]

            spot.save()

            print (spot)




            institution.name = forminstitution.cleaned_data["name"]

            institution.description = forminstitution.cleaned_data["description"]



            institution.spot = spot

            institution.save()


###########################  DEBUT Lundi ###########################

            horaires.days = "Lundi"
            horaires.institution = institution

            if request.POST['time_degin1l'] != "":
                horaires.time_degin = request.POST['time_degin1l']

            if request.POST['time_end1l'] != "":
                horaires.time_end = request.POST['time_end1l']

            if request.POST['time_degin2l'] != "":
                horaires.time_degin2 = request.POST['time_degin2l']

            if request.POST['time_end2l'] != "":
                horaires.time_end2 = request.POST['time_end2l']

            horaires.save()

###########################  Fin Lundi ###########################



###########################  DEBUT Mardi ###########################
            horaires1 = Horaires()


            horaires1.days =  "Mardi"
            horaires1.institution=institution

            if request.POST['time_degin1m'] != "":
                horaires1.time_degin = request.POST['time_degin1m']

            if request.POST['time_end1m'] != "":
                horaires1.time_end = request.POST['time_end1m']

            if request.POST['time_degin2m'] != "":
                horaires1.time_degin2 = request.POST['time_degin2m']

            if request.POST['time_end2m'] != "":
                horaires1.time_end2 = request.POST['time_end2m']

            horaires1.save()

###########################  FIN Mardi ###########################


###########################  DEBUT Mercredi ###########################
            horaires2 = Horaires()


            horaires2.days = "Mercredi"
            horaires2.institution = institution

            if request.POST['time_degin1me'] != "":
                horaires2.time_degin = request.POST['time_degin1me']

            if request.POST['time_end1me'] != "":
                horaires2.time_end = request.POST['time_end1me']

            if request.POST['time_degin2me'] != "":
                horaires2.time_degin2 = request.POST['time_degin2me']

            if request.POST['time_end2me'] != "":
                horaires2.time_end2 = request.POST['time_end2me']

            horaires2.save()

###########################  FIN Mercredi ###########################


###########################  DEBUT Jeudi ###########################
            horaires3 = Horaires()


            horaires3.days = "Jeudi"
            horaires3.institution = institution

            if request.POST['time_degin1j'] != "":
                horaires3.time_degin = request.POST['time_degin1j']

            if request.POST['time_end1j'] != "":
                horaires3.time_end = request.POST['time_end1j']

            if request.POST['time_degin2j'] != "":
                horaires3.time_degin2 = request.POST['time_degin2j']

            if request.POST['time_end2j'] != "":
                horaires3.time_end2 = request.POST['time_end2j']

            horaires3.save()

###########################  FIN Jeudi ###########################



###########################  DEBUT Vendredi ###########################

            horaires4 = Horaires()


            horaires4.days = "Vendredi"
            horaires4.institution = institution

            if request.POST['time_degin1v'] != "":
                horaires4.time_degin = request.POST['time_degin1v']

            if request.POST['time_end1v'] != "":
                horaires4.time_end = request.POST['time_end1v']

            if request.POST['time_degin2v'] != "":
                horaires4.time_degin2 = request.POST['time_degin2v']

            if request.POST['time_end2v'] != "":
                horaires4.time_end2 = request.POST['time_end2v']

            horaires4.save()

###########################  FIN Vendredi ###########################



###########################  DEBUT Samedi ###########################

            horaires5 = Horaires()


            horaires5.days = "Samedi"
            horaires5.institution = institution

            if request.POST['time_degin1s'] != "":
                horaires5.time_degin = request.POST['time_degin1s']

            if request.POST['time_end1s'] != "":
                horaires5.time_end = request.POST['time_end1s']

            if request.POST['time_degin2s'] != "":
                horaires5.time_degin2 = request.POST['time_degin2s']

            if request.POST['time_end2s'] != "":
                horaires5.time_end2 = request.POST['time_end2s']

            horaires5.save()

###########################  FIN Samedi ###########################


###########################  DEBUT Dimanche ###########################

            horaires6 = Horaires()


            horaires6.days = "Dimanche"
            horaires6.institution = institution

            if request.POST['time_degin1d'] != "":
                horaires6.time_degin = request.POST['time_degin1d']

            if request.POST['time_end1d'] != "":
                horaires6.time_end = request.POST['time_end1d']

            if request.POST['time_degin2d'] != "":
                horaires6.time_degin2 = request.POST['time_degin2d']

            if request.POST['time_end2d'] != "":
                horaires6.time_end2 = request.POST['time_end2d']

            horaires6.save()

###########################  FIN Dimanche ###########################




            card.file= form.cleaned_data["file"]

            card.jm_tag = str('jm_')+form.cleaned_data["jm_tag"]

            card.institution = institution

            card.category = form.cleaned_data["category"]

            card.is_public = form.cleaned_data["is_public"]

            card.owner = user

            card.save()

            cards = Card.objects.filter(owner=user)



            favourite_card = UserCardFavourite()

            favourite_card.sender = user

            favourite_card.date_created = datetime.now()

            favourite_card.save()

            favourite_card.card.add(card)



            cards = Card.objects.filter(owner=user)

            print (cards)

            if cards.count() > 0:

                page = '#page'

                return render(request, 'dashboard.html', locals())

            page = '#page'



            return render(request, 'dashboard.html',locals())

    else:

        form = CardForm()

        forminstitution = InstitutionForm()

        spotform = SpotForm()

        # horairesform = HorairesForm()

        cards = Card.objects.filter(owner=user)

    cards = Card.objects.filter(owner=user)

    return render(request, 'office/institutions/import.html',locals())















def new_event(request):

    us = request.session.get('id')

    user = User.objects.get(id=us)



    request.session['first_name'] = user.first_name

    request.session['last_name'] = user.last_name

    request.session['id'] = user.id

    request.session['telephone'] = user.telephone

    cards = Card.objects.filter(owner=user)

    print (cards)

    # if cards.count() > 0:

    #     page = '#page'

    #     return render(request, 'dashboard.html', locals())

    # page = 'page'



    if request.method == "POST":



        form = CardForm(request.POST, request.FILES)

        formevent = EventForm(request.POST, request.FILES)

        spotform = SpotForm(request.POST, request.FILES)

        chatgroupform = ChatGroupForm(request.POST, request.FILES)



        print (' Avant if ')

        if form.is_valid() and formevent.is_valid() and spotform.is_valid() and chatgroupform.is_valid():

            print (' Dans if ')

            spot = Spot()

            event = Event()

            card = Card()

            chatGroup =  ChatGroup()

            favourite_card = UserCardFavourite()


            cards = Card.objects.filter(jm_tag=str('jm_') + form.cleaned_data["jm_tag"])
            print (cards)
            # if (len(cards))==0:

            #    print ('COOL ')
            # else:
            #    print ('NON COOL ')




            if (len(cards)) == 0:
                print ('COOL ')
            else:
                message = "Ce « JM_Tag » existe déjà."
                a = Category.objects.all()
                return render(request, 'office/events/import.html', locals())



            spot.name = formevent.cleaned_data["name"]

            spot.latitude = spotform.cleaned_data["latitude"]

            spot.longitude = spotform.cleaned_data["longitude"]

            spot.save()

            print (spot)



            chatGroup.content = chatgroupform.cleaned_data["content"]

            chatGroup.userss = user


            chatGroup.save()
            chatGroup.users.add(user)


            print (chatGroup)





            event.name = formevent.cleaned_data["name"]

            event.description = formevent.cleaned_data["description"]

            event.date_begin = formevent.cleaned_data["date_begin"]

            event.date_end = formevent.cleaned_data["date_end"]

            event.spot = spot

            event.chatroom = chatGroup

            event.save()



            card.file= form.cleaned_data["file"]

            card.jm_tag = str('jm_')+form.cleaned_data["jm_tag"]

            card.event = event

            card.category = form.cleaned_data["category"]

            card.is_public = form.cleaned_data["is_public"]

            card.owner = user

            card.save()




            cards = Card.objects.filter(owner=user)


            favourite_card = UserCardFavourite()

            favourite_card.sender = user

            favourite_card.date_created = datetime.now()

            favourite_card.save()

            favourite_card.card.add(card)



            # favourite_card.save()

            cards = Card.objects.filter(owner=user)

            print (cards)

            if cards.count() > 0:

                page = '#page'

                return render(request, 'dashboard.html', locals())

            page = '#page'



            print ('Fin des cartes favorits')

            return render(request, 'dashboard.html', locals())

    else:

        print (' Else ')

        form = CardForm()

        formevent = EventForm()

        spotform = SpotForm()

        chatgroupform = ChatGroupForm()

        cards = Card.objects.filter(owner=user)

    cards = Card.objects.filter(owner=user)

    return render(request, 'office/events/import.html',locals())









### Bon
def edit_card(request):



    us = request.session.get('id')

    user = User.objects.get(id=us)



    request.session['first_name'] = user.first_name

    request.session['last_name'] = user.last_name

    request.session['id'] = user.id

    request.session['telephone'] = user.telephone

    cards = Card.objects.filter(owner=user)

    print(' AVANT METHOD ')

    print (cards)

    # if cards.count() > 0:

    #     page = '#page'

    #     return render(request, 'dashboard.html', locals())

    # page = 'page'



    if request.method=="POST":

        #id = request.GET.get('card')
        # print (' ID  ')
        # print (id)

        #card = Card.objects.get(id=id)

        # request.session['card_id'] = id

        print(' DANS METHOD 1')

        card0 = Card.objects.filter(id=request.session.get('card_id')).values('file', 'event__spot__id',
                                                                              'institution__spot__id',
                                                                              'event__spot__latitude',
                                                                              'event__spot__longitude',
                                                                              'institution__spot__latitude',
                                                                              'institution__spot__longitude',
                                                                              'event__name', 'institution__name',
                                                                              'event__date_begin', 'event__date_end',
                                                                              )
                                                                              # 'event__chatroom__content')

        # card = Card.objects.filter(id=request.session.get('card_id')).values('file',
        #                                                                      'institution__id',
        #                                                                      'institution__spot__id',
        #                                                                      'institution__spot__latitude',
        #                                                                      'institution__spot__longitude',
        #                                                                      'institution__name',
        #                                                                      'institution__date_begin',
        #                                                                      'institution__date_end')


        print(' DANS METHOD 2')
        print (card0)
        print (' VALEUR ')
        print (card0[0]['event__spot__id'])

        if card0[0]['event__spot__id'] == None:
            print (' Institutionnelle ')

            card1 = Card.objects.get(id=request.session.get('card_id'))
            card = Card.objects.filter(id=request.session.get('card_id')).values('file',
                                                                                 'institution__id',
                                                                                 'institution__spot__id',
                                                                                 'institution__spot__latitude',
                                                                                 'institution__spot__longitude',
                                                                                 'institution__name'
                                                                                 )

            insti = Institution.objects.get(id=card[0]['institution__id'])
            print (' INSTITUTION **** ')
            print (' INSTITUTION **** ')
            print (' INSTITUTION **** ')
            print (' INSTITUTION **** ')
            print (insti)

            print (card)
            print (' AVANT  Chatroom ')

            # formChat =ChatGroupForm(request.POST or None,instance=chatromms)
            formInstitution = InstitutionForm(instance=insti)
            print (' FORMULAIRE INSTITUTION ')
            print (formInstitution)


            horaires = Horaires.objects.filter(institution=card[0]['institution__id']).values('days',
                                                                                              'time_degin',
                                                                                              'time_end',
                                                                                              'time_degin2',
                                                                                              'time_end2',
                                                                                              'id')
            print (card[0]['institution__id'])
            print('horairess ******** ')
            print('horairess ******** ')
            print('horairess ******** ')
            print('horairess ******** ')
            print('horairess ******** ')
            print(horaires)



            # chatromms = ChatGroup.objects.filter(userss=user)
            # print (' Chatroom ')
            # print (chatromms)

            # events = Card.objects.get()
            # institution = Institution.objects.get()
            # chatromm = ChatGroup.objects.get()



            print (' La carte ')
            print (card)

            form = CardFormCustomize(request.POST, request.FILES, instance=card1)

            print (' Avant is valide')

            if form.is_valid():
                print (' DANS  is valide')


                if request.POST['ok']=='Supprimer':

                    print (' SUPRRESSION DE CARTE INSTITUTIONNELLE ')

                    request.session['first_name'] = user.first_name

                    request.session['last_name'] = user.last_name

                    request.session['id'] = user.id

                    request.session['telephone'] = user.telephone

                    cards = Card.objects.filter(owner=user)

                    print (cards)

                    # if cards.count() > 0:

                    #     page = '#page'

                    #     return render(request, 'dashboard.html', locals())

                    # page = 'page'


                    favorite = UserCardFavourite.objects.get(sender=user, card=card1)
                    print (' FAVORITE ')

                    favorite.delete()

                    card1.delete()


                    return render(request, 'dashboard.html', locals())



                else:

                    try:

                        request.session['first_name'] = user.first_name

                        request.session['last_name'] = user.last_name

                        request.session['id'] = user.id

                        request.session['telephone'] = user.telephone

                        cards = Card.objects.filter(owner=user)

                        card = Card.objects.filter(id=request.session.get('card_id')).values('file',
                                                                                             'institution__id',
                                                                                             'institution__spot__id',
                                                                                             'institution__spot__latitude',
                                                                                             'institution__spot__longitude',
                                                                                             'institution__name'
                                                                                             )

                        insti = Institution.objects.get(id=card[0]['institution__id'])
                        # print (insti)
                        #
                        #formInstitution = InstitutionForm(request.POST, request.FILES, instance=insti)
                        #
                        #insti.name = formInstitution.cleaned_data['name']
                        #insti.description = formInstitution.cleaned_data['description']
                        #insti.date_begin = formInstitution.cleaned_data['date_begin']
                        #insti.date_end = formInstitution.cleaned_data['date_end']


                        # formInstitution.save(commit=False)
                        # formInstitution.save_m2m()

                        insti.name = request.POST['name']
                        insti.description = request.POST['description']

                        print (' CC ')
                        print (insti.name)
                        # formInstitution.save()
                        insti.save()


                        horairesss = Horaires.objects.filter(institution=card[0]['institution__id']).values('days',
                                                                                                            'time_degin',
                                                                                                            'time_end',
                                                                                                            'time_degin2',
                                                                                                            'time_end2',
                                                                                                            'id')
                        print (horairesss)
                        print (' horairesss ----+++++++++1')
                        print (' horairesss ----+++++++++2')
                        print (horairesss[0]['id'])
                        # print(request.POST['time_degin[48]'])
                        print (' horairesss ----+++++++++222222+++++++++++++++')
                        print (' horairesss ----+++++++++222222')
                        print(request.POST['time_degin'+str(horairesss[0]['id'])])
                        print (' horairesss ----+++++++++3')
                        print (' horairesss ----+++++++++4')# horairesss[0][id]
                        print (horairesss[0])
                        print (horairesss[1])
                        print (horairesss[2])
                        print (horairesss[3])
                        print (horairesss[4])
                        print (horairesss[5])
                        print (horairesss[6])

                        # horairesss[0]['id']
                        print (' 1ere ')
                        print (' 1ere ')
                        print (' 1ere ')
                        print (' 1ere ')
                        print (request.POST['time_degin'+str(horairesss[0]['id'])])
                        print ('2ieme ')
                        print ('2ieme ')
                        print ('2ieme ')
                        print ('2ieme ')
                        print ('2ieme ')
                        print (request.POST['time_end'+str(horairesss[0]['id'])])



                        hor = Horaires.objects.get(id=horairesss[0]['id'])
                        if request.POST['time_degin'+str(horairesss[0]['id'])] == "":
                            hor.time_degin = None
                        else:
                            hor.time_degin = request.POST['time_degin' + str(horairesss[0]['id'])]

                        if request.POST['time_end'+str(horairesss[0]['id'])] == "":
                            hor.time_end = None
                        else:
                            hor.time_end = request.POST['time_end' + str(horairesss[0]['id'])]


                        if request.POST['time_degin2'+str(horairesss[0]['id'])] == "":
                            hor.time_degin2 = None
                        else:
                            hor.time_degin2 = request.POST['time_degin2' + str(horairesss[0]['id'])]


                        if request.POST['time_end2'+str(horairesss[0]['id'])] == "":
                            hor.time_end2 = None
                        else:
                            hor.time_end2 = request.POST['time_end2' + str(horairesss[0]['id'])]
                        hor.save()







                        hor1 = Horaires.objects.get(id=horairesss[1]['id'])
                        if request.POST['time_degin' + str(horairesss[1]['id'])] == "":
                            hor1.time_degin = None
                        else:
                            hor1.time_degin = request.POST['time_degin' + str(horairesss[1]['id'])]

                        if request.POST['time_end' + str(horairesss[1]['id'])] == "":
                            hor1.time_end = None
                        else:
                            hor1.time_end = request.POST['time_end' + str(horairesss[1]['id'])]

                        if request.POST['time_degin2' + str(horairesss[1]['id'])] == "":
                            hor1.time_degin2 = None
                        else:
                            hor1.time_degin2 = request.POST['time_degin2' + str(horairesss[1]['id'])]

                        if request.POST['time_end2' + str(horairesss[1]['id'])] == "":
                            hor1.time_end2 = None
                        else:
                            hor1.time_end2 = request.POST['time_end2' + str(horairesss[1]['id'])]
                        hor1.save()







                        hor2 = Horaires.objects.get(id=horairesss[2]['id'])
                        if request.POST['time_degin' + str(horairesss[2]['id'])] == "":
                            hor2.time_degin = None
                        else:
                            hor2.time_degin = request.POST['time_degin' + str(horairesss[2]['id'])]

                        if request.POST['time_end' + str(horairesss[2]['id'])] == "":
                            hor2.time_end = None
                        else:
                            hor2.time_end = request.POST['time_end' + str(horairesss[2]['id'])]

                        if request.POST['time_degin2' + str(horairesss[2]['id'])] == "":
                            hor2.time_degin2 = None
                        else:
                            hor2.time_degin2 = request.POST['time_degin2' + str(horairesss[2]['id'])]

                        if request.POST['time_end2' + str(horairesss[2]['id'])] == "":
                            hor2.time_end2 = None
                        else:
                            hor2.time_end2 = request.POST['time_end2' + str(horairesss[2]['id'])]
                        hor2.save()






                        hor3 = Horaires.objects.get(id=horairesss[3]['id'])
                        if request.POST['time_degin' + str(horairesss[3]['id'])] == "":
                            hor3.time_degin = None
                        else:
                            hor3.time_degin = request.POST['time_degin' + str(horairesss[3]['id'])]

                        if request.POST['time_end' + str(horairesss[3]['id'])] == "":
                            hor3.time_end = None
                        else:
                            hor3.time_end = request.POST['time_end' + str(horairesss[3]['id'])]

                        if request.POST['time_degin2' + str(horairesss[3]['id'])] == "":
                            hor3.time_degin2 = None
                        else:
                            hor3.time_degin2 = request.POST['time_degin2' + str(horairesss[3]['id'])]

                        if request.POST['time_end2' + str(horairesss[3]['id'])] == "":
                            hor3.time_end2 = None
                        else:
                            hor3.time_end2 = request.POST['time_end2' + str(horairesss[3]['id'])]
                        hor3.save()






                        hor4 = Horaires.objects.get(id=horairesss[4]['id'])
                        if request.POST['time_degin' + str(horairesss[4]['id'])] == "":
                            hor4.time_degin = None
                        else:
                            hor4.time_degin = request.POST['time_degin' + str(horairesss[4]['id'])]

                        if request.POST['time_end' + str(horairesss[4]['id'])] == "":
                            hor4.time_end = None
                        else:
                            hor4.time_end = request.POST['time_end' + str(horairesss[4]['id'])]

                        if request.POST['time_degin2' + str(horairesss[4]['id'])] == "":
                            hor4.time_degin2 = None
                        else:
                            hor4.time_degin2 = request.POST['time_degin2' + str(horairesss[4]['id'])]

                        if request.POST['time_end2' + str(horairesss[4]['id'])] == "":
                            hor4.time_end2 = None
                        else:
                            hor4.time_end2 = request.POST['time_end2' + str(horairesss[4]['id'])]
                        hor4.save()





                        hor5 = Horaires.objects.get(id=horairesss[5]['id'])
                        if request.POST['time_degin' + str(horairesss[5]['id'])] == "":
                            hor5.time_degin = None
                        else:
                            hor5.time_degin = request.POST['time_degin' + str(horairesss[5]['id'])]

                        if request.POST['time_end' + str(horairesss[5]['id'])] == "":
                            hor5.time_end = None
                        else:
                            hor5.time_end = request.POST['time_end' + str(horairesss[5]['id'])]

                        if request.POST['time_degin2' + str(horairesss[5]['id'])] == "":
                            hor5.time_degin2 = None
                        else:
                            hor5.time_degin2 = request.POST['time_degin2' + str(horairesss[5]['id'])]

                        if request.POST['time_end2' + str(horairesss[5]['id'])] == "":
                            hor5.time_end2 = None
                        else:
                            hor5.time_end2 = request.POST['time_end2' + str(horairesss[5]['id'])]
                        hor5.save()



                        hor6 = Horaires.objects.get(id=horairesss[6]['id'])
                        if request.POST['time_degin' + str(horairesss[6]['id'])] == "":
                            hor6.time_degin = None
                        else:
                            hor6.time_degin = request.POST['time_degin' + str(horairesss[6]['id'])]

                        if request.POST['time_end' + str(horairesss[6]['id'])] == "":
                            hor6.time_end = None
                        else:
                            hor6.time_end = request.POST['time_end' + str(horairesss[6]['id'])]

                        if request.POST['time_degin2' + str(horairesss[6]['id'])] == "":
                            hor6.time_degin2 = None
                        else:
                            hor6.time_degin2 = request.POST['time_degin2' + str(horairesss[6]['id'])]

                        if request.POST['time_end2' + str(horairesss[6]['id'])] == "":
                            hor6.time_end2 = None
                        else:
                            hor6.time_end2 = request.POST['time_end2' + str(horairesss[6]['id'])]
                        hor6.save()


                        form.save()

                        print (cards)

                        if cards.count() > 0:

                            page = '#page'

                            return render(request, 'dashboard.html', locals())

                        page = 'page'

                        return render(request, 'dashboard.html', locals())

                    except:

                        return render(request, 'dashboard.html', locals())




        else:

        # DEBUT IF EVENEMENTIELLE

            print(' METHOD POST EVENEMETIELLE ')

            card1 = Card.objects.get(id=request.session.get('card_id'))
            card = Card.objects.filter(id=request.session.get('card_id')).values('file',
                                                                                 'event__id',
                                                                                 'event__spot__id',
                                                                                 'event__spot__latitude',
                                                                                 'event__spot__longitude',
                                                                                 'event__name',
                                                                                 'event__date_begin',
                                                                                 'event__date_end',
                                                                                 'event__chatroom__id',
                                                                                 'event__chatroom__content')

            events = Event.objects.get(id=card[0]['event__id'])
            print (events)

            print (card)
            print (' AVANT  Chatroom ')
            chatromms = ChatGroup.objects.get(id=card[0]['event__chatroom__id'])

            formChat =ChatGroupForm(instance=chatromms)
            print (' CHAT FORMS ')

            formEvents = EventForm(instance=events)
            print (' EVENTS FORMS ')
            print (formEvents)

            # chatromms = ChatGroup.objects.filter(userss=user)
            # print (' Chatroom ')
            # print (chatromms)

            # events = Card.objects.get()
            # institution = Institution.objects.get()
            # chatromm = ChatGroup.objects.get()



            print (' La carte ')
            print (card)

            form = CardFormCustomize(request.POST, request.FILES, instance=card1)
            print(' SUPRESSION 0 ')

            if form.is_valid():
                print (' SUPRESSION DE CARTTE 1 ')

                if request.POST['ok'] == 'Supprimer':

                    request.session['first_name'] = user.first_name

                    request.session['last_name'] = user.last_name

                    request.session['id'] = user.id

                    request.session['telephone'] = user.telephone

                    cards = Card.objects.filter(owner=user)

                    print (cards)

                    # if cards.count() > 0:

                    #     page = '#page'

                    #     return render(request, 'dashboard.html', locals())

                    # page = 'page'



                    favorite = UserCardFavourite.objects.get(sender=user, card=card1)

                    print (' FAVORITE ')

                    favorite.delete()

                    card1.delete()


                    return render(request, 'dashboard.html', locals())



                else:

                    try:

                        print(' DEBUT ENREGISTREMENT ')
                        print(' DEBUT ENREGISTREMENT ')
                        print(' DEBUT ENREGISTREMENT ')
                        print(' DEBUT ENREGISTREMENT ')
                        print(' DEBUT ENREGISTREMENT ')

                        request.session['first_name'] = user.first_name

                        request.session['last_name'] = user.last_name

                        request.session['id'] = user.id

                        request.session['telephone'] = user.telephone

                        cards = Card.objects.filter(owner=user)

                        card = Card.objects.filter(id=request.session.get('card_id')).values('file',
                                                                                             'event__id',
                                                                                             'event__spot__id',
                                                                                             'event__spot__latitude',
                                                                                             'event__spot__longitude',
                                                                                             'event__name',
                                                                                             'event__date_begin',
                                                                                             'event__date_end',
                                                                                             'event__chatroom__id',
                                                                                             'event__chatroom__content')

                        print (card)





                        print(' DEBUT ENREGISTREMENT carte ')
                        print(' DEBUT ENREGISTREMENT carte ')
                        print(' DEBUT ENREGISTREMENT carte ')
                        print(' DEBUT ENREGISTREMENT carte ')

                        # Ancien la bonne
                        # chatromms.content = request.POST['content']
                        # chatromms.save()
                        # fIN LA BONNNE

                        chatromms = ChatGroup.objects.get(id=card[0]['event__chatroom__id'])

                        print ('debut chat ')
                        print ('debut chat ')
                        print ('debut chat ')
                        print ('debut chat ')
                        chatromms.content = request.POST['content']
                        chatromms.save()

                        print ('fin chat ')
                        print ('fin chat ')
                        print ('fin chat ')
                        print ('fin chat ')

                        eventss = Event.objects.get(id=card[0]['event__id'])
                        print ('eventss')
                        print (eventss)
                        eventss.name = request.POST['name']

                        eventss.save()

                        print ('name')
                        print (request.POST['name'])

                        eventss.description = request.POST['description']
                        eventss.save()

                        print ('desceiption')
                        print (request.POST['description'])

                        ########eventss.date_begin = request.POST['date_begin']
                        eventss.save()
                        form.save()





                        ###### eventss.date_end = request.POST['date_end']

                        a1 = str(request.POST['date_begin'])
                        print (a1)
                        a = request.POST['date_end']
                        print (a)

                        print (' date debut ')
                        print (' date debut ')


                        if eventss.date_begin ==a1:
                            print ('ok ')
                            print ('ok ')
                            print ('ok ')
                        else:
                            print ('Non OK ')
                            print ('Non OK ')
                            print ('Non OK ')
                            print ('Non OK ')

                        # print (dt)
                        print (' Fin')

                        # eventss.date_begin=request.POST['date_begin']
                        #dt = datetime.strptime(a1, '%d/%m/%Y %H:%M:%S')
                        # eventss.date_begin=dt
                        # print ('eventss.date_begin')
                        # print (eventss.date_begin)

                        # dt2 = datetime.strptime(a, '%d/%m/%Y %H:%M:%S')
                        # print (dt)


                        # eventss.date_end=dt2
                        print (' Fin 1')
                        eventss.date_begin=request.POST['date_begin']
                        eventss.date_end=request.POST['date_end']
                        eventss.save()
                        print (' Fin 2')

                        ### s = a1.strftime("%Y-%m-%d %H:%M:%S")
                        print ('s')
                        #### print (s)
                        print (' date fin ')
                        print (' date fin ')

                        eventss.save()

                        print(' DEBUT ENREGISTREMENT 0 ')

                        eventss.save()



                        # print (insti)
                        #
                        # formInstitution = InstitutionForm(request.POST, request.FILES, instance=insti)
                        #
                        # insti.name = formInstitution.cleaned_data['name']
                        # insti.description = formInstitution.cleaned_data['description']
                        # insti.date_begin = formInstitution.cleaned_data['date_begin']
                        # insti.date_end = formInstitution.cleaned_data['date_end']


                        # formInstitution.save()

                        # formEvents.save()
                        form.save()


                        print(' FIN ENREGISTREMENT ')
                        print(' FIN ENREGISTREMENT ')
                        print(' FIN ENREGISTREMENT ')
                        print(' FIN ENREGISTREMENT ')
                        print(' FIN ENREGISTREMENT ')


                        print (cards)


                        if cards.count() > 0:
                            page = '#page'

                            return render(request, 'dashboard.html', locals())

                        page = 'page'
                        return render(request, 'dashboard.html', locals())


                    except:

                        return render(request, 'dashboard.html', locals())
            return render(request, 'dashboard.html', locals())


            #card1.delete()
            #return render(request, 'dashboard.html', locals())









            # id = request.GET.get('card')

                #card = Card.objects.get(id=request.session.get('card_id'))

            # request.session['card_id'] = id
            # events = Event.objects.get(id=card[0]['event__id'])

                #formChat = ChatGroupForm(instance=chatromms)

                #formEvents = EventForm(instance=events)

                #form = CardFormCustomize(instance=card)

                #return render(request, 'editCard.html', locals())




        # FIN ELSE EVENEMETIELLE

    else:

        print ('  Au depart Evenementilles ')

        id=request.GET.get('card')

        card=Card.objects.get(id=id)

        request.session['card_id']=id

        card0 = Card.objects.filter(id=request.session.get('card_id')).values('file', 'event__spot__id',
                                                                              'institution__spot__id',
                                                                              'event__spot__latitude',
                                                                              'event__spot__longitude',
                                                                              'institution__spot__latitude',
                                                                              'institution__spot__longitude',
                                                                              'event__name', 'institution__name',
                                                                              'event__date_begin', 'event__date_end',
                                                                              'event__chatroom__content',
                                                                              'event__id','event__chatroom__id')
                                                                              #)

        if card0[0]['event__spot__id'] == None:


            cards = Card.objects.filter(id=request.session.get('card_id')).values('file',
                                                                                  'institution__id',
                                                                                  'institution__spot__id',
                                                                                  'institution__spot__latitude',
                                                                                  'institution__spot__longitude',
                                                                                  'institution__name'
                                                                                  )

            insti = Institution.objects.get(id=cards[0]['institution__id'])

            formInstitution = InstitutionForm(instance=insti)

            horaires = Horaires.objects.filter(institution=cards[0]['institution__id']).values('days',
                                                                                              'time_degin',
                                                                                              'time_end',
                                                                                              'time_degin2',
                                                                                              'time_end2',
                                                                                              'id')
            print (cards[0]['institution__id'])
            print('horairess ******** ')
            print('horairess ******** ')
            print('horairess ******** ')
            print('horairess ******** ')
            print('horairess ******** ')
            print(horaires)


            form=CardFormCustomize(instance=card)


            return render(request,'editCard.html',locals())

        else:

            print (' COOL ')

            eventss = Event.objects.get(id=card0[0]['event__id'])

            print (eventss)

            print (card)

            chatromms = ChatGroup.objects.get(id=card0[0]['event__chatroom__id'])

            formChat = ChatGroupForm(instance=chatromms)
            print (' AVANT  Chatroom ')
            print (formChat)

            formEvents = EventForm(instance=eventss)
            print (formEvents)

            form = CardFormCustomize(instance=card)
            print (form)

            return render(request, 'editCard.html', locals())

















def generator_k(size=5, chars=string.ascii_uppercase + string.digits):

    return ''.join(random.choice(chars) for _ in range(size))









def pixlr(request):

    a = Category.objects.all()

    image=request.GET.get('image')

    code =request.session.get('first_name')

    nom_carte_po=code+generator_k()+'.jpg'

    request.session['nom_carte_po'] =nom_carte_po

    fullfilename = os.path.join('media/cards/', nom_carte_po)

    print (fullfilename)

    urllib.request.urlretrieve(image, fullfilename)

    #urllib.urlretrieve(image, "local-filename.jpg")

    print ('salam')

    return  render(request,'office/institutions/create_institution_card.html', {'category':a})

    # return  render(request, 'create_po.html', locals())









def event_pixlr(request):

    a = Category.objects.all()

    image=request.GET.get('image')

    code =request.session.get('first_name')

    nom_carte_po=code+generator_k()+'.jpg'

    request.session['nom_carte_po'] =nom_carte_po

    fullfilename = os.path.join('media/cards/', nom_carte_po)

    print (fullfilename)

    urllib.request.urlretrieve(image, fullfilename)

    #urllib.urlretrieve(image, "local-filename.jpg")

    print ('salam')



    # print (category)

    # return  render(request,'office/events/create_events_card.html', locals())

    return  render(request,'office/events/create_events_card.html', {'category':a})



	# return  render(request, 'create_po.html', locals())

	

	

	

	

def save_pixlr_event(request):



	#code=request.session.get('code')

	#user=Utilisateur.objects.get(code=code)

	
    try:

        us = request.session.get('id')

        user = User.objects.get(id=us)



        request.session['first_name'] = user.first_name

        request.session['last_name'] = user.last_name

        request.session['id'] = user.id

        request.session['telephone'] = user.telephone






        event = Event()

        spot = Spot()

        card = Card()

        categoryy = Category()

        favourite_card = UserCardFavourite()

        chatGroup = ChatGroup()



        cards = Card.objects.filter(jm_tag=str('jm_') + request.POST["jm_tag"])
        print (cards)

        if (len(cards)) == 0:
            print ('COOL ')
        else:
            name_event = request.session['name_event']
            latitude = request.session['latitude']
            longitude = request.session['longitude']
            description = request.session['description']

            content = request.session['content']
            is_public = request.session['is_public']


            message = "Ce « JM_Tag » existe déjà."

            card.file = str('/cards/') + request.session.get('nom_carte_po')

            category = Category.objects.all()
            return render(request, 'office/events/create_events_card.html', locals())



        category = Category.objects.get(id=request.POST["category"])





        spot.name = request.POST["name_event"]

        spot.latitude = request.POST["latitude"]

        spot.longitude = request.POST["longitude"]

        spot.save()


        print('Fin du spot ')


        chatGroup.content = request.POST["content"]

        chatGroup.created = datetime.now()

        chatGroup.userss = user

        chatGroup.save()

        chatGroup.users.add(user)

        print (' Fin du Chat Group ')




        event.name = request.POST["name_event"]

        event.description = request.POST["description"]

        event.spot = spot

        event.date_begin = request.POST["date_begin"]

        event.date_end = request.POST["date_end"]

        event.chatroom = chatGroup

        event.save()



        print('Fin de l evenement ')





        card.file= str('/cards/')+request.session.get('nom_carte_po')

        card.jm_tag = str('/cards/')+request.POST["jm_tag"]

        card.event = event

        card.category = category

        card.is_public = request.POST["is_public"]

        card.owner = user

        card.save()



        print('Fin de la carte ')



        favourite_card.sender = user

        favourite_card.date_created = datetime.now()

        favourite_card.save()

        favourite_card.card.add(card)

        #favourite_card.save()



        print ('Fin des cartes favorits')





        cards = Card.objects.filter(owner=user)

        print (cards)

        if cards.count() > 0:

            page = '#page'

            return render(request, 'dashboard.html', locals())

        page = '#page'





        return render(request, 'dashboard.html', {})

    except:

        message = "Echec de L enregistrement"
        return render(request, 'office/events/create_events_card.html', {"message":message})



def save_pixlr_institution(request):



    #code=request.session.get('code')

    #user=Utilisateur.objects.get(code=code)
    try:


        us = request.session.get('id')

        user = User.objects.get(id=us)



        request.session['first_name'] = user.first_name

        request.session['last_name'] = user.last_name

        request.session['id'] = user.id

        request.session['telephone'] = user.telephone





        institution = Institution()

        spot = Spot()

        card = Card()

        categoryy = Category()

        horaires = Horaires()

        favourite_card = UserCardFavourite()



        cards = Card.objects.filter(jm_tag=str('jm_') + request.POST["jm_tag"])
        print(cards)

        if (len(cards)) == 0:
            print('COOL ')
        else:

            name_institution = request.session['name_institution']
            latitude = request.session['latitude']
            longitude = request.session['longitude']
            description = request.session['description']

            time_degin1l = request.session['time_degin1l']
            time_end1l = request.session['time_end1l']
            time_degin2l = request.session['time_degin2l']
            time_end2l = request.session['time_end2l']

            time_degin1m = request.session['time_degin1m']
            time_end1m = request.session['time_end1m']
            time_degin2m = request.session['time_degin2m']
            time_end2m = request.session['time_end2m']

            time_degin1me = request.session['time_degin1me']
            time_end1me = request.session['time_end1me']
            time_degin2me = request.session['time_degin2me']
            time_end2me = request.session['time_end2me']

            time_degin1j = request.session['time_degin1j']
            time_end1j = request.session['time_end1j']
            time_degin2j = request.session['time_degin2j']
            time_end2j = request.session['time_end2j']

            time_degin1v = request.session['time_degin1v']
            time_end1v = request.session['time_end1v']
            time_degin2v = request.session['time_degin2v']
            time_end2v = request.session['time_end2v']

            time_degin1s = request.session['time_degin1s']
            time_end1s = request.session['time_end1s']
            time_degin2s = request.session['time_degin2s']
            time_end2s = request.session['time_end2s']

            time_degin1d = request.session['time_degin1d']
            time_end1d = request.session['time_end1d']
            time_degin2d = request.session['time_degin2d']
            time_end2d = request.session['time_end2d']

            is_public = request.session['is_public']

            message = "Ce « JM_Tag » existe déjà."
            card.file = str('/cards/') + request.session.get('nom_carte_po')
            category = Category.objects.all()

            return render(request, 'office/institutions/create_institution_card.html', locals())



        category = Category.objects.get(id=request.POST["category"])





        spot.name = request.POST["name_institution"]

        spot.latitude = request.POST["latitude"]

        spot.longitude = request.POST["longitude"]

        spot.save()



        print('Fin du spot ')







        institution.name = request.POST["name_institution"]

        institution.description = request.POST["description"]

        institution.spot = spot

        institution.save()
        print('Fin de l institution ')


        ###################### Debut Horaires #############################


        ###########################  Fin Lundi ###########################


        horaires.days = "Lundi"
        horaires.institution = institution

        if request.POST['time_degin1l'] != "":
            horaires.time_degin = request.POST['time_degin1l']

        if request.POST['time_end1l'] != "":
            horaires.time_end = request.POST['time_end1l']

        if request.POST['time_degin2l'] != "":
            horaires.time_degin2 = request.POST['time_degin2l']

        if request.POST['time_end2l'] != "":
            horaires.time_end2 = request.POST['time_end2l']

        horaires.save()

        ###########################  Fin Lundi ###########################



        ###########################  DEBUT Mardi ###########################
        horaires1 = Horaires()

        horaires1.days = "Mardi"
        horaires1.institution = institution

        if request.POST['time_degin1m'] != "":
            horaires1.time_degin = request.POST['time_degin1m']

        if request.POST['time_end1m'] != "":
            horaires1.time_end = request.POST['time_end1m']

        if request.POST['time_degin2m'] != "":
            horaires1.time_degin2 = request.POST['time_degin2m']

        if request.POST['time_end2m'] != "":
            horaires1.time_end2 = request.POST['time_end2m']

        horaires1.save()

        ###########################  FIN Mardi ###########################


        ###########################  DEBUT Mercredi ###########################
        horaires2 = Horaires()

        horaires2.days = "Mercredi"
        horaires2.institution = institution

        if request.POST['time_degin1me'] != "":
            horaires2.time_degin = request.POST['time_degin1me']

        if request.POST['time_end1me'] != "":
            horaires2.time_end = request.POST['time_end1me']

        if request.POST['time_degin2me'] != "":
            horaires2.time_degin2 = request.POST['time_degin2me']

        if request.POST['time_end2me'] != "":
            horaires2.time_end2 = request.POST['time_end2me']

        horaires2.save()

        ###########################  FIN Mercredi ###########################


        ###########################  DEBUT Jeudi ###########################
        horaires3 = Horaires()

        horaires3.days = "Jeudi"
        horaires3.institution = institution

        if request.POST['time_degin1j'] != "":
            horaires3.time_degin = request.POST['time_degin1j']

        if request.POST['time_end1j'] != "":
            horaires3.time_end = request.POST['time_end1j']

        if request.POST['time_degin2j'] != "":
            horaires3.time_degin2 = request.POST['time_degin2j']

        if request.POST['time_end2j'] != "":
            horaires3.time_end2 = request.POST['time_end2j']

        horaires3.save()

        ###########################  FIN Jeudi ###########################



        ###########################  DEBUT Vendredi ###########################

        horaires4 = Horaires()

        horaires4.days = "Vendredi"
        horaires4.institution = institution

        if request.POST['time_degin1v'] != "":
            horaires4.time_degin = request.POST['time_degin1v']

        if request.POST['time_end1v'] != "":
            horaires4.time_end = request.POST['time_end1v']

        if request.POST['time_degin2v'] != "":
            horaires4.time_degin2 = request.POST['time_degin2v']

        if request.POST['time_end2v'] != "":
            horaires4.time_end2 = request.POST['time_end2v']

        horaires4.save()

        ###########################  FIN Vendredi ###########################



        ###########################  DEBUT Samedi ###########################

        horaires5 = Horaires()

        horaires5.days = "Samedi"
        horaires5.institution = institution

        if request.POST['time_degin1s'] != "":
            horaires5.time_degin = request.POST['time_degin1s']

        if request.POST['time_end1s'] != "":
            horaires5.time_end = request.POST['time_end1s']

        if request.POST['time_degin2s'] != "":
            horaires5.time_degin2 = request.POST['time_degin2s']

        if request.POST['time_end2s'] != "":
            horaires5.time_end2 = request.POST['time_end2s']

        horaires5.save()

        ###########################  FIN Samedi ###########################


        ###########################  DEBUT Dimanche ###########################

        horaires6 = Horaires()

        horaires6.days = "Dimanche"
        horaires6.institution = institution

        if request.POST['time_degin1d'] != "":
            horaires6.time_degin = request.POST['time_degin1d']

        if request.POST['time_end1d'] != "":
            horaires6.time_end = request.POST['time_end1d']

        if request.POST['time_degin2d'] != "":
            horaires6.time_degin2 = request.POST['time_degin2d']

        if request.POST['time_end2d'] != "":
            horaires6.time_end2 = request.POST['time_end2d']

        horaires6.save()

        ###########################  FIN Dimanche ###########################




        ####################### Fin Horaires  ############################







        card.file= str('/cards/')+request.session.get('nom_carte_po')

        card.jm_tag = str('jm_')+request.POST["jm_tag"]

        card.institution = institution

        card.category = category

        # a = request.POST.getlist("is_public")
        #if not a :
            #a = False
        #else:
        #    a = True


        card.is_public = request.POST["is_public"]

        card.owner = user

        card.save()



        print('Fin de la carte ')



        favourite_card.sender = user

        favourite_card.date_created = datetime.now()
        favourite_card.save()

        favourite_card.card.add(card)
        #favourite_card.save()

        print ('Fin des cartes favorits')

        cards = Card.objects.filter(owner=user)

        print (cards)

        if cards.count() > 0:

            page = '#page'

            return render(request, 'dashboard.html', locals())

        page = '#page'

        return render(request, 'dashboard.html', locals())

    except:
        message = "Ce « JM_Tag » existe déjà."
        return render(request, 'office/institutions/create_institution_card.html', {"message": message})








def save_pixlr_event2(request):	


	us = request.session.get('id')

	user = User.objects.get(id=us)



	request.session['first_name'] = user.first_name

	request.session['last_name'] = user.last_name

	request.session['id'] = user.id

	request.session['telephone'] = user.telephone

	

	if request.method == "POST":



		form = CardForm(request.POST, request.FILES)

		formevent = EventForm(request.POST, request.FILES)

		spotform = SpotForm(request.POST, request.FILES)





		if form.is_valid() and formevent.is_valid() and spotform.is_valid():



			spot = Spot()

			event = Event()

			card = Card()



			spot.name = spotform.cleaned_data["name"]

			spot.latitude = spotform.cleaned_data["latitude"]

			spot.longitude = spotform.cleaned_data["longitude"]

			spot.save()

			print (spot)



			event.name = formevent.cleaned_data["name"]

			event.description = formevent.cleaned_data["description"]

			event.spot = spot

			event.save()



			card.file= request.session.get('nom_carte_po')

			card.jm_tag = form.cleaned_data["jm_tag"]

			card.event = event

			card.category = form.cleaned_data["category"]

			card.is_public = form.cleaned_data["is_public"]

			card.owner = user

			card.save()



			return render(request, 'dashboard.html')

	else:

		form = CardForm()

		formevent = EventForm()

		spotform = SpotForm()



	return render(request, 'office/events/create_events_card.html',locals())

