# 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 gettext as _
from datetime import datetime
from django.contrib.auth.decorators import login_required
from .funcs import *
from GeneralApp.funcs import get_inter_http_respose

def registration_View(request):

    Dict = {}

    t = loader.get_template('pages/profile/p_registration.html')
    return get_inter_http_respose(t, Dict, request)
    # return HttpResponse(t.render(Dict, request))


# def create_route_for_customer_View(request):
#     Dict = {}
#     t = loader.get_template('pages/profile/p_user_profile.html')
#     return HttpResponse(t.render(Dict, request))
#
#
# def create_route_for_mover_View(request):
#     Dict = {}
#     t = loader.get_template('pages/profile/p_user_profile.html')
#     return HttpResponse(t.render(Dict, request))


@login_required(login_url='/profile/login/')
def profile_page_View(request, page_name, id=None):
    Dict = {
        'page_html': get_profile_page_content_html(request, page_name, id),
        'page_name': page_name,
        'page_type': 'profile'
    }

    t = loader.get_template('pages/profile/p_user_profile.html')
    return get_inter_http_respose(t, Dict, request)
    # return HttpResponse(t.render(Dict, request))


# @login_required(login_url='/profile/login/')
# def chat_w_user_View(request, user_id=None):
#     from ChatServiceApp.funcs import get_chat_page_content_Dict
#
#     # receivers = get_chat_receivers_for_user(request.user)
#
#     Dict = get_chat_page_content_Dict(request, user_id)
#
#     # cur_chat_msgs = None
#     #
#     # try:
#     #     cur_receiver = User.objects.get(id=user_id)
#     #     if not cur_receiver in receivers:
#     #         receivers.insert(0, cur_receiver)
#     #     cur_chat_msgs = get_msgs_for_chat_w_users(request.user, cur_receiver)
#     # except User.DoesNotExist:
#     #     cur_receiver = None
#     #
#     #
#     # Dict = {
#     #     'page': 'chat',
#     #     'cur_receiver': cur_receiver,
#     #     'receivers': receivers,
#     #     'messages':cur_chat_msgs
#     # }
#
#     t = loader.get_template('pages/profile/p_user_profile.html')
#     return HttpResponse(t.render(Dict, request))

@login_required(login_url='/profile/login/')
def user_profile_View(request):

    Dict = {}

    user_online = request.session.get('online', False)
    # request.COOKIES['user_id'] = request.user.id

    t = loader.get_template('pages/profile/p_user_profile.html')
    response = get_inter_http_respose(t, Dict, request)
    # response =  HttpResponse(t.render(Dict, request))
    response.set_cookie('user_id', request.user.id)
    return response


def logout_View(request):
    from django.contrib.auth import logout
    from django.shortcuts import redirect

    logout(request)
    return redirect('login_profile')

def login_View(request):

    Dict = {}

    t = loader.get_template('pages/profile/p_login.html')
    return get_inter_http_respose(t, Dict, request)
    # return HttpResponse(t.render(Dict, request))




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'])

        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 recovery_password_user(request, uidb64=None, token=None):
    from django.contrib.auth.views import PasswordResetConfirmView

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




def create_temporary_user():
    from django.utils.translation import gettext 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