# coding=utf-8
from BaseModels.mailSender import techSendMail

from ..models import *
from datetime import date, datetime
from GeneralApp.views import get_timestamp_by_property_item_name, set_timestamp_by_propertiy_item_name
from BaseModels.error_processing import *
from uuid import uuid1
from GeneralApp.temp_data_funcs import add_tmp_data, del_tmp_data_by_obj

def avg(val):
    """uses floating-point division."""
    return sum(val) / float(len(val))


from django.http import HttpResponse
import json

def import_1C_pocket_from_file(request):

    if not request.user.is_superuser:
        return HttpResponse(u'import_1C_pocket_from_file PERMISSION FAIL')

    try:
        f = open('companies_1s.txt')
        data = f.read()
    except:
        return HttpResponse(u'import_1C_pocket_from_file READ FILE FAIL')

    import re
    data = re.sub(r'[\r\n\t]', ' ', data)
    data = re.sub(r'\s+', ' ', data)

    request_data = data

    data = json.loads(request_data)

    import_1C_pocket(data)

    return HttpResponse(u'import_1C_pocket_from_file Accept')


def import_1C_pocket(json_data):


    log = ''
    log_begin_DT = datetime.now()
    msg = 'import_1C_pocket MANAGERS start - {0}<br>---------------<br><br>'.format(str(log_begin_DT))
    log = '{0}<br>{1}'.format(log, msg)

    try:
        data = json_data['data_list']
        timestamp = json_data['timestamp']
        msg = str(timestamp)
        log = '{0}<br>{1}'.format(log, msg)

        # dt = datetime.fromtimestamp(timestamp)

        saved_timestamp = get_timestamp_by_property_item_name('1S_managers')

        if saved_timestamp and saved_timestamp >= timestamp:
            # generate_error(f, u'import_1S_companies', u'1S_companies пакет устарел, импорт не был произведен', u'')
            msg = '<b style="color : red;">!!!!! --- 1S_managers пакет устарел, импорт не был произведен</b>'
            print(msg)
            return {u'result': u'1S_managers пакет устарел, импорт не был произведен', 'error': 304}
        set_timestamp_by_propertiy_item_name('1S_managers', timestamp)
    except:
        data = json_data

    # сохраняем данные для импорта временно в БД
    tmp_data = add_tmp_data(data_type='import_proc', data_target='managers_1s_import', data=data)


    for item in data:
        # print(str(item))
        # break

        json_item = json.dumps(item, ensure_ascii=False)

        try:
            if not u'id' in item:
                # generate_error(f, u'import_1S_companies', u'1S_companies ID отсутствует в экзепляре данных', json_item)
                msg = '<b style="color : red;">!!!!! --- 1S_managers ID отсутствует в экзепляре данных</b>'
                log = '{0}<br>{1}'.format(log, msg)
                return {
                    u'result': msg,
                    u'error': 400,

                }

            msg = '{0} - {1}'.format(item[u'id'], item[u'name'])
            log = '{0}<br>{1}'.format(log, msg)

            user_profiles = UserProfile.objects.filter(id_1s=item[u'id'])


            kwargs = {
                'name' : item[u'name'].replace(u"'", '"'),
                'id_1s' : item[u'id'],
                'company_position' : item[u'position'],
                'departament': str(item[u'subdiv']),
            }

            work_start_D = item[u'datein'].replace(u" ", '')
            if len(work_start_D) > 9:
                work_start_D = datetime.strptime(work_start_D, "%d.%m.%Y")
                kwargs.update({'work_start_D' : work_start_D})

            work_finish_D = item[u'dateout'].replace(u" ", '')
            if len(work_finish_D) > 9:
                work_finish_D = datetime.strptime(work_finish_D, "%d.%m.%Y")
                kwargs.update({'work_finish_D': work_finish_D})

            birthday = item[u'birthday'].replace(u" ", '')
            if len(birthday) > 9:
                birthday = datetime.strptime(birthday, "%d.%m.%Y")
                kwargs.update({'birthdate': birthday})



            user = None
            u_profile = None
            if user_profiles:
                user_profiles.update(**kwargs)
                u_profile = user_profiles[0]
                msg = ' - ОБНОВЛЕНИЕ данных МЕНЕДЖЕРА - {0}'.format(str(u_profile.__dict__))
                user = u_profile.user

            if not user:
                username = str(item[u'id'])
                mail = '{0}@truenergy.by'.format(str(item[u'id']))
                password = user_id = str(uuid1().hex)[:10]
                user = User.objects.create_user(username=username, email=mail, password=password)
                user.is_staff = True
                user.is_active = True
                user.is_superuser = False
                user.set_password(password)
                user.save()

                kwargs.update({'user': user})

                user_profiles = UserProfile.objects.filter(user=user)
                user_profiles.update(**kwargs)
                u_profile = user_profiles[0]

                msg = ' - СОЗДАНИЕ МЕНЕДЖЕРА - {0}'.format(str(u_profile.__dict__))

            log = '{0}<br>{1}'.format(log, msg)

            msg = ''
            if 'work_finish_D' in kwargs and user.is_active:
               user.is_active = False
               msg = ' - отключен доступ<br>'
            name_list = item[u'name'].split(' ')
            if len(name_list) > 1 and user.first_name != ' '.join(name_list[1:]):
                user.first_name = ' '.join(name_list[1:])
                msg = ' - изменено имя<br>'
            if len(name_list) > 0 and user.last_name != name_list[0]:
                user.last_name = name_list[0]
                msg = ' - изменена фамилия'

            if msg:
                user.save()
                log = '{0}<br>{1}'.format(log, msg)



        except Exception as e:
            # generate_error(f, u'import_1S_companies', str(e), json_item)
            msg = '<b style="color : red;">!!!!! --- import_1C_pocket MANAGERS error={0}</b>'.format(str(e))
            print(msg)
            log = '{0}<br>{1}'.format(log, msg)

        # close_log_file(f, u'END import_1S_companies')

    # удаляем временные данные для импорта из БД
    if tmp_data:
        del_tmp_data_by_obj(tmp_data)

    msg = 'import_1C_package MANAGERS finish - {0} (processing time = {1}<br>---------------<br><br>'.format(
        str(datetime.now()),
        str(datetime.now() - log_begin_DT)
    )
    log = '{0}<br>{1}'.format(log, msg)

    title = 'import_1C_pocket MANAGERS'
    techSendMail(log, title)

    return {
        u'result': log
    }



