
import sys

from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.db import transaction
from rest_framework.decorators import permission_classes, authentication_classes

import json

from rest_framework.authentication import (
    SessionAuthentication, 
    BasicAuthentication, 
    TokenAuthentication
)

from rest_framework.permissions import IsAuthenticated

from account.models import UserProfile
from iltshot.models import (
    Phone, 
    PhotoCustomer, 
    ShotOperation, 
    Exam, 
    Serie,
    StudentIDNumber
)

from iltshot.api.serializers import (
    PhoneSerializer, 
    PhotoCustomerSerializer,
    ExamSerializer,
    SerieSerializer
)

from iltshot.api import tools as ShotTools
from iltshot.api import errorcode

@transaction.atomic
@api_view(['POST',])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def take_shot(request):
    if request.method == 'POST':
        try:
            try:
                debit = request.data['debit']
                registrationNumber = request.data['matricule']
            except Exception:
                return Response({
                    "code":errorcode.BAD_MESSAGE_FORMAT, 
                    "errormsg":"Bad message format.", 
                    'data':{}
                    },
                    status=status.HTTP_400_BAD_REQUEST)

            try:
                userprofile = UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                return Response({
                    "code":errorcode.UNKNOWN_PROFILE, 
                    "errormsg":"Unknown profile.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            if userprofile is not None and userprofile.customer is None:
                return Response({
                    "code":errorcode.ISNOT_ILT_CUSTOMER_USER, 
                    "errormsg":"Profile not link to a customer.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                phone = Phone.objects.get(phone_id=request.data['phone_id'])
            except Phone.DoesNotExist:
                return Response({
                    "code":errorcode.PHONE_DOES_NOT_EXIST, 
                    "errormsg":"Unknown phone ID.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)
            
            if phone.phone_state == 'I':
                return Response({
                    "code":errorcode.PHONE_IS_NOT_ACTIVE, 
                    "errormsg":"This phone is not activated.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                photocustomer = PhotoCustomer.objects.get(customer=userprofile.customer)
            except PhotoCustomer.DoesNotExist:
                return Response({
                    "code":errorcode.ISNOT_ILT_SHOT_CUSTOMER, 
                    "errormsg":"Is not an ILT customer for SAGEES Photo solution.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            balance = ShotTools.get_customer_balance(photocustomer)
            if balance <= 0:
                return Response({
                    "code":errorcode.NOT_ENOUGH_CREDIT, 
                    "errormsg":"Not enough credit.", 
                    'data':{
                        'customerbalance':balance
                        }
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                student = StudentIDNumber.objects.get(registration_number=registrationNumber)

                resp = {}
                resp['code'] = errorcode.OK_RESPONSE_CODE
                resp['errormsg'] = ''

                data = {}
                data['phone_id'] = phone.phone_id
                data['phone_name'] = phone.phone_name
                data['debit'] = debit
                data['customerbalance'] = balance

                resp['data'] = data
                return Response(resp, status=status.HTTP_200_OK)

            except StudentIDNumber.DoesNotExist:
                std = StudentIDNumber(
                    registration_number=registrationNumber,
                    customer = photocustomer)
                std.save()

            shotoperation = ShotOperation(
                shotoperation_name='Take a Shot',
                shotoperation_type="D",
                shotoperation_debit=request.data['debit'],
                customer=photocustomer,
                phone=phone,
                customerprofile=userprofile
            )        
            shotoperation.save()

            resp = {}
            resp['code'] = errorcode.OK_RESPONSE_CODE
            resp['errormsg'] = ''

            data = {}
            data['phone_id'] = shotoperation.phone.phone_id
            data['phone_name'] = shotoperation.phone.phone_name
            data['debit'] = shotoperation.shotoperation_debit
            data['customerbalance'] = balance - int(shotoperation.shotoperation_debit)

            resp['data'] = data

            return Response(resp, status=status.HTTP_200_OK)
        except Exception as error:
            return  Response({
                "code":errorcode.SERVER_ERROR, 
                'errormsg':'System ERROR -> ' + str(sys.exc_info()),
                'data':{}
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        
@transaction.atomic
@api_view(['POST',])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def register_phone(request):
    if request.method == 'POST':
        try:
            try:
                userprofile = UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                return Response({
                    "code":errorcode.UNKNOWN_PROFILE, 
                    "errormsg":"Unknown profile.", 
                    'data':{}
                    }, 
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                phone = Phone.objects.get(phone_id=request.data['phone_id'])
                phone_exist = True
            except Phone.DoesNotExist:
                phone_exist = False

            if phone_exist:
                return Response({
                    "code":errorcode.DUPLICATED_PHONE_ID, 
                    "errormsg":"This phone ID is already used/registered.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                photocustomer = PhotoCustomer.objects.get(customer=userprofile.customer)
            except PhotoCustomer.DoesNotExist:
                return Response({
                    "code":errorcode.ISNOT_ILT_SHOT_CUSTOMER, 
                    "errormsg":"Is not an ILT customer for SAGEES Photo solution.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            if request.user.is_superuser:
                phone = Phone(
                    phone_id=request.data['phone_id'],
                    phone_name=request.data['phone_name'],
                    phone_state='A',
                    customer=photocustomer
                )
            else:
                phone = Phone(
                    phone_id=request.data['phone_id'],
                    phone_name=request.data['phone_name'],
                    customer=photocustomer
                )
            phone.save()

            resp = {}
            resp['code'] = errorcode.OK_RESPONSE_CODE
            resp['errormsg'] = ''

            data = {}
            data['phone_id'] = phone.phone_id
            data['phone_name'] = phone.phone_name
            data['phone_state'] = phone.phone_state

            resp['data'] = data

            return Response(resp, status=status.HTTP_200_OK)
        except Exception as error:
            print("ERROR :", str(sys.exc_info()))
            return  Response({
                "code":errorcode.SERVER_ERROR, 
                'errormsg':'System ERROR -> ' + str(sys.exc_info()),
                'data':{}
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@transaction.atomic
@api_view(['POST',])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def activate_phone(request):
    if request.method == 'POST':
        try:
            if not request.user.is_staff:
                return Response({
                    "code":errorcode.PERMISSION_DENIED, 
                    "errormsg":"Only an administrator can activate a phone.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                userprofile = UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                return Response({
                    "code":errorcode.UNKNOWN_PROFILE, 
                    "errormsg":"Unknown profile.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                photocustomer = PhotoCustomer.objects.get(customer=userprofile.customer)
            except PhotoCustomer.DoesNotExist:
                return Response({
                    "code":errorcode.ISNOT_ILT_SHOT_CUSTOMER, 
                    "errormsg":"Is not an ILT customer for SAGEES Photo solution.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                phone = Phone.objects.get(phone_id=request.data['phone_id'], customer=photocustomer)
            except Phone.DoesNotExist:
                return Response({
                    "code":errorcode.PHONE_DOES_NOT_EXIST, 
                    "errormsg":"Unregistered phone.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)
                
            phone.phone_state = 'A'
            phone.save()

            resp = {}
            resp['code'] = errorcode.OK_RESPONSE_CODE
            resp['errormsg'] = ''

            data = {}
            data['phone_id'] = phone.phone_id
            data['phone_name'] = phone.phone_name
            data['phone_state'] = phone.phone_state

            resp['data'] = data

            return Response(resp, status=status.HTTP_200_OK)
        except Exception as error:
            return  Response({
                "code":errorcode.SERVER_ERROR, 
                'errormsg':'System ERROR -> ' + str(sys.exc_info()),
                'data':{}
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@transaction.atomic
@api_view(['POST',])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def deactivate_phone(request):
    if request.method == 'POST':
        try:
            if not request.user.is_staff:
                return Response({
                    "code":errorcode.PERMISSION_DENIED, 
                    "errormsg":"Only an administrator can deactivate a phone.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                userprofile = UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                return Response({
                    "code":errorcode.UNKNOWN_PROFILE, 
                    "errormsg":"Unknown profile.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                photocustomer = PhotoCustomer.objects.get(customer=userprofile.customer)
            except PhotoCustomer.DoesNotExist:
                return Response({
                    "code":errorcode.ISNOT_ILT_SHOT_CUSTOMER, 
                    "errormsg":"Is not an ILT customer for SAGEES Photo solution.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                phone = Phone.objects.get(phone_id=request.data['phone_id'], customer=photocustomer)
            except Phone.DoesNotExist:
                return Response({
                    "code":errorcode.PHONE_DOES_NOT_EXIST, 
                    "errormsg":"Unregistered phone.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)
                
            phone.phone_state = 'I'
            phone.save()

            resp = {}
            resp['code'] = errorcode.OK_RESPONSE_CODE
            resp['errormsg'] = ''

            data = {}
            data['phone_id'] = phone.phone_id
            data['phone_name'] = phone.phone_name
            data['phone_state'] = phone.phone_state

            resp['data'] = data

            return Response(resp, status=status.HTTP_200_OK)
        except Exception as error:
            return  Response({
                "code":errorcode.SERVER_ERROR, 
                'errormsg':'System ERROR -> ' + str(sys.exc_info()),
                'data':{}
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET',])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def phones_list(request):
    if request.method == 'GET':
        try:
            if not request.user.is_staff:
                return Response({
                    "code":errorcode.PERMISSION_DENIED, 
                    "errormsg":"Only an administrator can see this list.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                userprofile = UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                return Response({
                    "code":errorcode.UNKNOWN_PROFILE, 
                    "errormsg":"Unknown profile.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                photocustomer = PhotoCustomer.objects.get(customer=userprofile.customer)
            except PhotoCustomer.DoesNotExist:
                return Response({
                    "code":errorcode.ISNOT_ILT_SHOT_CUSTOMER, 
                    "errormsg":"Is not an ILT customer for SAGEES Photo solution.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            phones = Phone.objects.filter(customer=photocustomer)
            serializer = PhoneSerializer(phones, many=True)

            resp = {}
            resp['code'] = errorcode.OK_RESPONSE_CODE
            resp['errormsg'] = ''
            resp['data'] = serializer.data

            return Response(resp, status=status.HTTP_200_OK)
        except Exception as error:
            return  Response({
                "code":errorcode.SERVER_ERROR, 
                'errormsg':'System ERROR -> ' + str(sys.exc_info()),
                'data':{}
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET',])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def get_balance(request):
    if request.method == 'GET':
        try:
            try:
                userprofile = UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                return Response({
                    "code":errorcode.UNKNOWN_PROFILE, 
                    "errormsg":"Unknown profile.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                photocustomer = PhotoCustomer.objects.get(customer=userprofile.customer)
            except PhotoCustomer.DoesNotExist:
                return Response({
                    "code":errorcode.ISNOT_ILT_SHOT_CUSTOMER, 
                    "errormsg":"Is not an ILT customer for SAGEES Photo solution.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            balance = ShotTools.get_customer_balance(photocustomer)
            resp = {}
            resp['code'] = errorcode.OK_RESPONSE_CODE
            resp['errormsg'] = ''
            resp['data'] = {'balance':balance}

            return Response(resp, status=status.HTTP_200_OK)
        except Exception as error:
            return  Response({
                "code":errorcode.SERVER_ERROR, 
                'errormsg':'System ERROR -> ' + str(sys.exc_info()),
                'data':{}
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@transaction.atomic
@api_view(['POST',])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def push_school_data(request):
    if request.method == 'POST':
        try:
            if not request.user.is_staff:
                return Response({
                    "code":errorcode.PERMISSION_DENIED, 
                    "errormsg":"Only an administrator can deactivate a phone.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)
                
            try:
                userprofile = UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                return Response({
                    "code":errorcode.UNKNOWN_PROFILE, 
                    "errormsg":"Unknown profile.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                photocustomer = PhotoCustomer.objects.get(customer=userprofile.customer)
            except PhotoCustomer.DoesNotExist:
                return Response({
                    "code":errorcode.ISNOT_ILT_SHOT_CUSTOMER, 
                    "errormsg":"Is not an ILT customer for SAGEES Photo solution.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            photocustomer.photocustomer_classeslist = json.dumps(request.data['classes'])
            photocustomer.photocustomer_studentslist = json.dumps(request.data['students']) 
            photocustomer.save()

            resp = {}
            resp['code'] = errorcode.OK_RESPONSE_CODE
            resp['errormsg'] = ''
            resp['data'] = {}

            return Response(resp, status=status.HTTP_200_OK)
        except Exception as error:
            return  Response({
                "code":errorcode.SERVER_ERROR, 
                'errormsg':'System ERROR -> ' + str(sys.exc_info()),
                'data':{}
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@transaction.atomic
@api_view(['GET',])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def pull_school_data(request):
    if request.method == 'GET':
        try:                
            try:
                userprofile = UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                return Response({
                    "code":errorcode.UNKNOWN_PROFILE, 
                    "errormsg":"Unknown profile.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                photocustomer = PhotoCustomer.objects.get(customer=userprofile.customer)
            except PhotoCustomer.DoesNotExist:
                return Response({
                    "code":errorcode.ISNOT_ILT_SHOT_CUSTOMER, 
                    "errormsg":"Is not an ILT customer for SAGEES Photo solution.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            exams = Exam.objects.filter(state='E')
            examserializer = ExamSerializer(exams, many=True)

            series = Serie.objects.filter(state='E')
            serieserializer = SerieSerializer(series, many=True)

            #print("examserializer.data = ", examserializer.data)
            if examserializer.data is not None:
                exam_series = []
                if examserializer.data is not None:
                    for ee in examserializer.data:
                        #print("ee = ", ee)
                        series_exam = ee["series"]
                        for ss in series_exam:
                            exam_series.append({
                                'exam_code':ee["exam_code"], 
                                'serie_code':ss["serie_code"] 
                                })

            balance = ShotTools.get_customer_balance(photocustomer)
            customer = userprofile.customer

            #print('Classe = ', photocustomer.photocustomer_classeslist, 'len = ', len(photocustomer.photocustomer_classeslist))
            classes = {}   
            cl_list =  photocustomer.photocustomer_classeslist
            if  (cl_list is not None) and (len(cl_list.rstrip()) > 0): 
                #print('not none classes')      
                classes= json.loads(photocustomer.photocustomer_classeslist)

            #print('student = ', photocustomer.photocustomer_studentslist, 'len = ', len(photocustomer.photocustomer_classeslist))
            students = {}            
            std_list =  photocustomer.photocustomer_studentslist
            if std_list is not None and (len(std_list.rstrip()) > 0):   
                #print('not none students')      
                students = json.loads(photocustomer.photocustomer_studentslist)
            #print("classes : ", type(classes), classes)
            #print("students : ", type(students), students)

            resp = {}
            resp["code"] = errorcode.OK_RESPONSE_CODE
            resp["errormsg"] = ""
            resp["data"] = {
                "classes":classes, 
                "students":students,
                'exams':examserializer.data,
                'series':serieserializer.data,
                'exam_series':exam_series,
                "school_name":customer.customer_name,
                "customerstatus":{
                    "balance":balance,
                    "requiredconnexion":photocustomer.photocustomer_requiredconnexion
                }
            }

            return Response(resp, status=status.HTTP_200_OK)
        except Exception as error:
            return  Response({
                "code":errorcode.SERVER_ERROR, 
                'errormsg':'System ERROR -> ' + str(sys.exc_info()),
                'data':{}
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET',])
def shot_customers_list(request):
    if request.method == 'GET':
        try:
            photocustomers = PhotoCustomer.objects.filter(state='E')
            serializer = PhotoCustomerSerializer(photocustomers, many=True)
            data = []
            for val in serializer.data:
                customer = val['customer']
                data.append({
                    'id':customer['id'], 
                    'customer_name':customer['customer_name'], 
                    'customer_address':customer['customer_address']
                    })

            resp = {}
            resp['response'] = 'success'
            resp['errormsg'] = ''
            resp['data'] = data

            return Response(resp, status=status.HTTP_200_OK)
        except Exception as error:
            return  Response({
                "code":errorcode.SERVER_ERROR, 
                'errormsg':'System ERROR -> ' + str(sys.exc_info()),
                'data':{}
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@transaction.atomic
@api_view(['POST',])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def off_line_shot(request):
    """
    Précondition : On etait déjà a on line shot et on aimerai passé a off line shot
    Est appeler pour prendre les photos hors connexion.
    Dans ce cas, il faut s'assurer qu'on n'a plus d'apareil photo actif
    """
    if request.method == 'POST':
        try:
            if not request.user.is_superuser:
                return Response({
                    "code":errorcode.PERMISSION_DENIED, 
                    "errormsg":"Only the superuser can do this operation.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)
                
            try:
                userprofile = UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                return Response({
                    "code":errorcode.UNKNOWN_PROFILE, 
                    "errormsg":"Unknown profile.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                photocustomer = PhotoCustomer.objects.get(customer=userprofile.customer)
            except PhotoCustomer.DoesNotExist:
                return Response({
                    "code":errorcode.ISNOT_ILT_SHOT_CUSTOMER, 
                    "errormsg":"Is not an ILT customer for SAGEES Photo solution.", 
                    'data':{}
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            phones = Phone.objects.filter(customer=photocustomer).filter(phone_id!=request.data['phone_id']).filter(phone_state='A')
            if len(phones) > 0:
                serializer = PhoneSerializer(phones, many=True)
                return Response({
                    "code":errorcode.CAN_NOT_HAVE_MANY_ACTIVE_PHONE_OFF_LINE, 
                    "errormsg":"There is other active phones.", 
                    'data':serializer.data
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            photocustomer.photocustomer_requiredconnexion = False
            photocustomer.save()

            balance = ShotTools.get_customer_balance(photocustomer)
            resp = {}
            resp['code'] = errorcode.OK_RESPONSE_CODE
            resp['errormsg'] = ''
            resp['data'] = {
                'photocustomer_requiredconnexion': False,
                'balance':balance
                }

            return Response(resp, status=status.HTTP_200_OK)
        except Exception as error:
            return  Response({
                "code":errorcode.SERVER_ERROR, 
                'errormsg':'System ERROR -> ' + str(sys.exc_info()),
                'data':{}
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@transaction.atomic
@api_view(['POST',])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def on_line_shot(request):
    """
    Précondition : On etait déjà en mode OFF line SHOT et on aimerai passé a ON line SHOT
    Est appeler pour prendre les photos ON LINE.
    Seul le super utilisateur peut effectuer cette opération
    """
    if request.method == 'POST':
        try:
            if not request.user.is_superuser:
                return Response({
                    "code":errorcode.PERMISSION_DENIED, "errormsg":"Only the superuser can do this operation.", 'data':{}},
                    status=status.HTTP_401_UNAUTHORIZED)
                
            try:
                userprofile = UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                return Response({
                    "code":errorcode.UNKNOWN_PROFILE, "errormsg":"Unknown profile.", 'data':{}},
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                photocustomer = PhotoCustomer.objects.get(customer=userprofile.customer)
            except PhotoCustomer.DoesNotExist:
                return Response({
                    "code":errorcode.ISNOT_ILT_SHOT_CUSTOMER, "errormsg":"Is not an ILT customer for SAGEES Photo solution.", 'data':{}},
                    status=status.HTTP_401_UNAUTHORIZED)

            photocustomer.photocustomer_requiredconnexion = True
            photocustomer.save()
            balance = ShotTools.get_customer_balance(photocustomer)

            resp = {}
            resp['code'] = errorcode.OK_RESPONSE_CODE
            resp['errormsg'] = ''
            resp['data'] = {
                'photocustomer_requiredconnexion': True,
                'balance':balance
                }

            return Response(resp, status=status.HTTP_200_OK)
        except Exception as error:
            return  Response({
                "code":errorcode.SERVER_ERROR, 
                'errormsg':'System ERROR -> ' + str(sys.exc_info()),
                'data':{}},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
