# -*- coding: utf-8 -*-
"""Public access (need identification for data access)."""

from outils.common_imports import *
from outils.for_view_imports import *
from outils.images_imports import *

from members.models import CagetteMember
from shifts.models import CagetteShift

from django.contrib.auth.hashers import check_password, make_password


def _get_response_according_credentials(request, credentials, context, template):
    response = HttpResponse(template.render(context, request))
    if ('token' in credentials and 'auth_token' in credentials):
        response.set_cookie('id', credentials['id'])
        response.set_cookie('token', credentials['token'])
        response.set_cookie('auth_token', credentials['auth_token'])
        response.set_cookie('deconnect_option', 'true')
    return response

def info_perso(request):
    from outils.functions import extract_firstname_lastname
    # coop_logger.info('On cherche à accéder à la page info perso')
    context = {'title': 'Informations Personnelles',
               'info_perso': True}
    if hasattr(settings, 'WITH_WEBSITE_MENU'):
        context['with_website_menu'] = settings.WITH_WEBSITE_MENU
    template = loader.get_template('website/personnal_data.html')
    credentials = CagetteMember.get_credentials(request)

    if ('failure' in credentials):
        template = loader.get_template('website/connect.html')
        context['msg'] = ''
        if 'msg' in credentials:
            context['msg'] = credentials['msg']
        context['password_placeholder'] = 'Naissance (jjmmaaaa)'
    else:
        from datetime import datetime
        if 'id' in request.COOKIES:
            partner_id = request.COOKIES['id']
        else:
            partner_id = credentials['id']
        m = CagetteMember(partner_id)
        m_data = m.get_data(full=True)
        # recupérer 'partner_owned_share_ids'
        if len(m_data) > 0:
            template_data = m_data[0]
            img_src = ''
            if template_data['image_medium']:
                try:
                    img_code = base64.b64decode(template_data['image_medium'])
                    extension = imghdr.what('', img_code)
                    img_src = 'data:image/'+extension+';base64,'+template_data['image_medium']
                except:
                    pass
            else:
                # empty picture with instructions
                img_full_path = 'outils/static/img/empty_coop_picture_130.png'
                if hasattr(settings, 'EMPTY_COOP_PICTURE'):
                    img_full_path = settings.EMPTY_COOP_PICTURE
                with open(img_full_path, 'rb') as imgFile:
                    image = base64.b64encode(imgFile.read())
                    img_src = 'data:image/png;base64,' + image.decode('utf-8')
            template_data['img_src'] = img_src
            name_sep = ' '
            if hasattr(settings, 'SUBSCRIPTION_NAME_SEP'):
                name_sep = settings.SUBSCRIPTION_NAME_SEP
            template_data['name_sep'] = name_sep
            name_elts = extract_firstname_lastname(template_data['name'], name_sep)
            template_data['lastname'] = name_elts['lastname']
            if name_elts['firstname'] != name_elts['lastname']:
                template_data['firstname'] = name_elts['firstname']
            else:
                template_data['firstname'] = ''
            template_data['cooperative_state'] = CagetteMember.get_state_fr(template_data['cooperative_state'])
            try:
                template_data['create_date'] = datetime.strptime(template_data['create_date'], '%Y-%m-%d %H:%M:%S')
                if template_data['date_alert_stop']:
                    template_data['date_alert_stop'] = datetime.strptime(template_data['date_alert_stop'], '%Y-%m-%d')
                if template_data['date_delay_stop']:
                    template_data['date_delay_stop'] = datetime.strptime(template_data['date_delay_stop'], '%Y-%m-%d')
            except:
                pass

            context['data'] = template_data
        else: # no member found corresponding to partner_id
            return redirect('/website/deconnect')
    return _get_response_according_credentials(request, credentials, context, template)

def update_info_perso(request):
    result = {}
    credentials = CagetteMember.get_credentials(request)

    if ('failure' in credentials):
        result['error'] = 'forbidden'
    else:
        if 'id' in request.COOKIES:
            partner_id = request.COOKIES['id']
        else:
            partner_id = credentials['id']
        m = CagetteMember(partner_id)
        result['process'] = m.update_from_ajax(request)

    return JsonResponse({'res': result})

def deconnect(request):
    referer = request.META.get('HTTP_REFERER')
    redirect_url = '/'
    if referer and len(referer) > 0:
        redirect_url = referer
    response = redirect(redirect_url)
    response.delete_cookie('id', '/')
    response.delete_cookie('token', '/')
    response.delete_cookie('auth_token', '/')
    response.delete_cookie('deconnect_option', '/')
    return response

def forgotten_pwd(request):
    if request.method == 'GET':
        template = loader.get_template('website/get_email.html')
        context = {'email_placeholder': 'Votre email',
                   'title': 'Mot de passe oublié'}
        response = HttpResponse(template.render(context, request))
    else:
        send_res = CagetteMember.send_new_password_link(request)
        response = JsonResponse({'res': send_res})

    return response

def change_pwd(request):
    if request.method == 'GET':
        template = loader.get_template('website/change_pwd.html')
        context = {'password_placeholder': 'Nouveau mot de passe',
                   'title': 'Changer de mot de passe'}
        response = HttpResponse(template.render(context, request))
    else:
        #  TODO
        return JsonResponse({}, safe=False)
    return response
