# coding=utf-8
from BaseModels.api.base_api_views import *
from ..models import *
from rest_framework.response import Response
from BaseModels.mailSender import techSendMail
import json
from BaseModels.api.base_api_permissions import *
from datetime import datetime
import re
from rest_framework import status
from BaseModels.api.base_api_serializers import Import_Pocket_Srializer



class Managers_1C_get_timestamp(APIBaseSimplaClass):

    permission_classes = (api_1C_perm,)
    serializer_class = Import_Pocket_Srializer

    def get(self, request):
        from GeneralApp.views import get_timestamp_by_property_item_name

        property_item_name = u'1S_managers'

        last_timestamp = get_timestamp_by_property_item_name(property_item_name)

        return Response({
            'property_item_name' : property_item_name,
            'timestamp' : last_timestamp
        })


class Managers_1C_import(APIBaseSimplaClass):

    # authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (api_1C_perm,)
    serializer_class = Import_Pocket_Srializer

    def post(self, request, format=None):
        """
        import 1C companies data
        """

        log = ''
        res = ''

        try:

            data = request.data

            if not data:
                msg = 'нет данных в пакете'
                res_Dict = {
                    'status': 'error',
                    'error': msg
                }
                return Response(res_Dict, status=status.HTTP_400_BAD_REQUEST)


            from .import_1C_data import import_1C_pocket
            res = import_1C_pocket(data)

            res_Dict = {
                'status': 'finished',
                'log': log
            }
            res_Dict.update(res)

            return Response(res_Dict)

        except Exception as e:
            len_data = 0
            if request.data:
                len_data = len(request.data)
            title = 'ОШИБКА tE Managers_1C_import'
            msg = 'Managers_1C_import Error = {0}({1})<br>lenght data = {2}<br>log...<br>{3}'.format(
                str(e), str(e.args), str(len_data), str(res)
            )
            from BaseModels.mailSender import techSendMail_for_specified_email_list
            from tEDataProj.inter import problem_solvers_personal_1S
            techSendMail_for_specified_email_list(msg, problem_solvers_personal_1S, title=title)

            res_Dict = {
                'status': 'error',
                'error': str(e)
            }

            return Response(res_Dict, status=status.HTTP_400_BAD_REQUEST)