# coding=utf-8

from django.shortcuts import render

from uuid import uuid1
from AuthApp.models import *
from django.contrib import auth
from django.http import HttpResponse, Http404
from django.template import loader, RequestContext
from django.contrib.auth.decorators import login_required
from BaseModels.mailSender import techSendMail
from django.utils.translation import ugettext as _
from datetime import datetime


def create_personal_user(data, creator):

    try:

        user_id = str(uuid1().hex)[:10]
        user_name = data['email']
        mail = user_name
        user = User.objects.create_user(username=user_name, email=mail, password=user_id)

        if 'first_name' in data and data['first_name']:
            user.first_name = data['first_name']
        if 'last_name' in data and data['last_name']:
            user.last_name = data['last_name']
        user.is_staff = False
        user.is_active = False
        user.is_superuser = False
        # user.set_password(user_id)
        user.save()

        user_communications_ads_list = []

        if 'office__name' in data['user_profile']:
            del data['user_profile']['office__name']
        if 'communications' in data['user_profile']:

            user_communications_ads_list.extend(data['user_profile']['communications'])
            del data['user_profile']['communications']

        if not 'creator' in data['user_profile'] and creator:
            data['user_profile']['creator'] = creator

        profiles = UserProfile.objects.filter(user=user).update(**data['user_profile'])

        if user_communications_ads_list:
            from GeneralApp.funcs import create_communications_items_by_list
            comm_objs = create_communications_items_by_list(user.user_profile, user_communications_ads_list)

        user.refresh_from_db()

        return {
            'name' : mail,
            'pass' : user_id,
            'user' : user
        }
    except Exception as e:
        return {
            'error': 'Ошибка добавление нового пользователя = {0}'.format(str(e)),
        }



def decode_get_param(data):
    import base64
    import json

    d = data['data'].encode()
    token_data = base64.b64decode(d)

    try:
        request_data = token_data.decode('utf8')
    except:
        request_data = token_data

    data = json.loads(request_data)

    return data

def check_user_key(data):
    # print(u'check_user_key')


    # try:
    #     user_id = int(data[0])
    # except:
    #     user_id = None
    # try:
    #     user1S_id = int(data[1])
    #
    # company_id = data[2]
    # user_key = data[3]

    res = u'Key Broken'
    # user_id = data[u'userId']
    # user_key = data[u'userKey']
    # user1S_id = data['user1S_id']
    # company_id = data[u'companyId']

    data = decode_get_param(data)

    try:
        token = UserTokens.objects.get(
            user_id=data['pk'],
            user_key=data['code'],
            user1S_id=data['1S_pk'],
            company_id = data['comp_pk']
        )
        res = u'Accept'
        # print(u'try1 ok')
    except UserTokens.DoesNotExist:
        # если не найден id и ключ
        try:
            token = UserTokens.objects.get(
                user_id=data['pk']
            )
            # techSendMail(
            #     u'user try access by id={0}, key={1}, c_id={2}'.format(
            #         str(user_id),
            #         str(user_key),
            #         str(company_id)
            #     )
            # )

            res = u'Key Broken'
            # print(u'try2 ok')
        except UserTokens.DoesNotExist:
            # если не найден id
            token = UserTokens.objects.create(
                user_id=data['pk'],
                user_key=data['code'],
                company_id=data['comp_pk']
            )
            res = u'Accept'
            # print(u'except ok')

    return res



def recovery_password_user(request, uidb64=None, token=None):
    from django.contrib.auth.views import PasswordResetConfirmView

    return PasswordResetConfirmView(request=request, uidb64=uidb64, token=token
    )


# def recovery_password_user_complete(request, user_id, authCode):
#     from django.contrib.auth.forms import SetPasswordForm
#     from AuthApp.funcs import sendActivationMail
#
#     try:
#         user = User.objects.get(id=user_id, mipp_user__authMailCode=authCode)
#
#     except:
#         user = None
#
#     if user:
#
#         user.set_password()
#
#         if reg_user.is_active:
#             activated_early = True
#         else:
#             reg_user.backend = 'AuthApp.backends.BaldeniniAuthBackend'
#             login(request, reg_user)
#
#             reg_user.is_active = True
#             reg_user.save()
#             sendActivationMail(reg_user)
#
#     else:
#         raise Http404
#         # print(reg_user)
#
#     context = {
#         'user': user,
#         'activated_early' : activated_early,
#         }
#
#     t = loader.get_template('pages/profile.html')
#
#     rContext = RequestContext(request, context)
#     return HttpResponse(t.render(rContext))



# def check_user_registration_and_activate(request, user_id, authCode):
#     from django.contrib.auth import authenticate, login
#     from AuthApp.funcs import sendActivationMail
#
#     try:
#         reg_user = User.objects.get(id=user_id, mipp_user__authMailCode=authCode)
#
#     except:
#         reg_user = None
#
#     activated_early = False
#
#     if reg_user:
#
#         if reg_user.is_active:
#             activated_early = True
#         else:
#             reg_user.backend = 'AuthApp.backends.BaldeniniAuthBackend'
#             login(request, reg_user)
#
#             reg_user.is_active = True
#             reg_user.save()
#             sendActivationMail(reg_user)
#
#     else:
#         raise Http404
#         # print(reg_user)
#
#     context = {
#         'reg_user': reg_user,
#         'activated_early' : activated_early,
#         }
#
#
#
#     t = loader.get_template('admin_pages/pages/Profile/profile.html')
#
#     # rContext = RequestContext(request, context)
#     # return HttpResponse(t.render(rContext))
#     return HttpResponse(t.render(context, request))



def create_temporary_user():
    from django.utils.translation import ugettext as _
    user_id = str(uuid1().hex)[:10]
    user_name = u'user'+user_id
    mail = user_id+u'@truenergy.by'
    user = User.objects.create_user(mail, mail,user_id)
    user.first_name = _(u'незарег. пользователь')
    user.last_name = u''
    user.is_staff = False
    user.is_active = True
    user.is_superuser = False
    user.set_password(user_id)
    # print(u'user_create_pass', user.password)
    # p = user.get_profile()
    # p.address = ''
    # p.phone = ''
    # p.group = None
    # p.discount = 0
    # p.pay_balance = 0
    # p.authMailCode = uuid1().hex
    # p.save()

    user.save()
    user.mipp_user.temporary_user = True
    user.mipp_user.save()
    # print('user',user)
    # print('created profile',p)
    # print('user created', user)
    return {
        'name' : mail,
        'pass' : user_id,
        'user' : user
    }


def get_active_user(request):
    if request.user.is_anonymous:
        return None
    else:
        user = request.user
        # try:
        #     bd = user.mipp_user.birthdate
        # except MIPPUser.DoesNotExist:
        #     MIPPUser.objects.create(user=user)

        return user


def get_active_user_if_anonymous_create_temporary(request):

    user = get_active_user(request)

    if not user:
        new_user_Dict = create_temporary_user()
        user = auth.authenticate(username=new_user_Dict['name'], password=new_user_Dict['pass'])
        if user:
            auth.login(request, user)

    return user