import time
from  generic.gn_request   import   Request # 
from  generic.gn_gamarra    import   gn_gamarra #
from datetime import datetime

import json
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


class gamarra(gn_gamarra):
    
    def __init__(self, argv:list):
        self.response = None
        self.db = False
        self.output_count = 0
        self.suffix = "app_generic" 
        self.unparsed_data = {}
        self.setup(argv)
        
        self.rote_handler()
        
        apiKey = self.get_token_data('apiKey')

        self.gamarra_request = Request(
            base_url = self.environment_config.get('url'),
            params   = {},
            verify= False,
            headers={
                'x-api-key': apiKey,
                'content-type': 'application/json'
            }
        )
         
        super(gamarra, self, ).__init__(argv)
        
        print('Fim')

    # ------------------------------------------------------------------#
    #   GET /health                                                     #   
    # ------------------------------------------------------------------#   
    
    def health_handler(self, extra):

        data = self.gamarra_request.doRequest(
            rote = self.rote,
            method = "GET"
        )

        status = "OK" if data.status_code == 200 else "ER"
        msg_status = "API DISPONIVEL" if status == "OK" else "API INDISPONIVEL"

        saida = "{status}|{msg_status}".format(
            status=status,
            msg_status=msg_status,
        )

        self.write_file(saida, self.saida_cobol, 'w+', 'ISO-8859-1')

    # ------------------------------------------------------------------#
    #   GET /usuarios                                                   #   
    # ------------------------------------------------------------------#   
    
    def usuarios_handler(self, extra):

        data = self.gamarra_request.doRequest(
            rote = self.rote,
            method = "GET"
        )

        status = "OK" if data.status_code == 200 else "ER"
        msg_status = data.text if data.status_code != 200 else ""
        
        if status == "OK":
            dados = json.loads(data.text)

            flag = "w+"
            index = 0
            
            for usuario in dados:
                saida = "{status}|{msg_status}|{cod_usuario}|{nome}".format(
                    status=status,
                    msg_status=msg_status,
                    cod_usuario=usuario['CodUsuario'],
                    nome=usuario['Nome']
                )

                if index > 1:
                    flag = "a+"
                    saida = "\n" + saida

                self.write_file(saida, self.saida_cobol, flag, 'ISO-8859-1')

                index += 1

    # ------------------------------------------------------------------#
    #   GET /clientexserial                                             #   
    # ------------------------------------------------------------------#   
    
    def clientexserial_handler(self, extra):
        serial = self.rote_data['query']['serial']
        url = "{rote}?serial={serial}".format(rote=self.rote, serial=serial)

        data = self.gamarra_request.doRequest(
            rote = url,
            method = "GET"
        )

        status = "OK" if data.status_code == 200 else "ER"
        msg_status = data.text if data.status_code != 200 else ""
        cod_cliente = ""
        
        if status == "OK":
            dados = json.loads(data.text)

            flag = "w+"
            index = 0

            if 'obs' in dados:
                self.write_file("ER|{obs}".format(obs=dados['obs']), self.saida_cobol, flag, encoding='ISO-8859-1')
                return
            
            for cliente in dados:
                saida = "{status}|{msg_status}|{cod_cliente}|{serial}".format(
                    status=status,
                    msg_status=msg_status,
                    cod_cliente=cliente['CodCliente'],
                    serial=serial
                )

                if index > 0:
                    flag = "a+"
                    saida = "\n" + saida

                self.write_file(saida, self.saida_cobol, flag, 'ISO-8859-1')

                index += 1

    # ------------------------------------------------------------------#
    #   GET /serialxcliente                                             #   
    # ------------------------------------------------------------------#   
    
    def serialxcliente_handler(self, extra):
        cod_cliente = self.rote_data['query']['codcliente']
        url = "{rote}?codcliente={cod_cliente}".format(rote=self.rote, cod_cliente=cod_cliente)

        data = self.gamarra_request.doRequest(
            rote = url,
            method = "GET"
        )

        status = "OK" if data.status_code == 200 else "ER"
        msg_status = data.text if data.status_code != 200 else ""
        serial = ""
        
        if status == "OK":
            dados = json.loads(data.text)

            flag = "w+"
            index = 0

            if 'obs' in dados:
                self.write_file("ER|{obs}".format(obs=dados['obs']), self.saida_cobol, flag, encoding='ISO-8859-1')
                return


            for serial in dados:
                saida = "{status}|{msg_status}|{cod_cliente}|{serial}".format(
                    status=status,
                    msg_status=msg_status,
                    serial=serial['Serial'],
                    cod_cliente=cod_cliente
                )

                if index > 0:
                    flag = "a+"
                    saida = "\n" + saida

                self.write_file(saida, self.saida_cobol, flag, encoding='ISO-8859-1')

                index += 1
            
        
            
    # ------------------------------------------------------------------#
    #                                                                   #
    #   ROTA DE CRIAÇÃO DE PEDIDOS                                      #   
    #                                                                   #
    # ------------------------------------------------------------------#
                
    def post_route_handler_pedido(self):
        #""" Rota de inclusao e alteracao de pedido tratamento de envio"""
        data = self.txt_to_dict()
        data_parsed = None

        for request in data.get('C'):
            self.unparsed_data  = request

            request_structure   = self.atualWs.get('request')

            if data_parsed == None:
                data_parsed  = self.parser(request, request_structure)
                data_parsed['itens'] = []
            else:
                data_parsed['itens'].append({
                    "codigo": request['itens_codigo']['valor'],
                    "serial": request['itens_serial']['valor'],
                    "qtd": request['itens_qtd']['valor']
                })

        self.handle_send(data_parsed)
            
    def beforeSend_pedido(self, data):
        return
    
    # Tratamento do retorno da criação de pedidos
    def handle_output_pedido(self, data):
        response = json.loads(self.gamarra_request.req.text) if self.gamarra_request.req.status_code in [200, 400]  else None
        status = ""
        msg_status = ""

        if response == None:
            status = "ER"
            msg_status == "Houve um erro de comunicação, verificar tokens e conexão"

        if not response == None:
            try:
                status = "OK" if response['status'] == "sucesso" else "ER"
                msg_status = response['obs']

                saida = "{status}|{msg_status}".format(
                    status=status,
                    msg_status=msg_status,
                )

                self.write_file(saida, self.saida_cobol, 'w+', encoding='ISO-8859-1')
            except:
                saida = "OK|sucesso"
                # saida = "ER|pedido com itens com erro" if any(item.get('status', '').startswith('erro') for item in response['itens']) else "OK|sucesso"

                self.write_file(saida, self.saida_cobol, 'w+', encoding='ISO-8859-1')

                for item in response['itens']:
                    if "status" in item and item['status'].startswith("erro"):
                        saida = "\nER|" + item['status']

                        self.write_file(saida, self.saida_cobol, 'a+', encoding='ISO-8859-1')
                    else:
                        saida = "\nOK|" + item['status']

                        self.write_file(saida, self.saida_cobol, 'a+', encoding='ISO-8859-1')
       
        return 
    
    # ----------------------------------------------------------------- #
    # ------------------------------------------------------------------#
    #                                                                   #
    #   ROTA DE CRIAÇÃO DE CLIENTE                                      #   
    #                                                                   #
    # ------------------------------------------------------------------#
                
    def post_route_handler_cliente(self):
        #""" Rota de inclusao e alteracao de pedido tratamento de envio"""
        data = self.txt_to_dict()

        for request in data.get('C'):
            self.unparsed_data  = request
            
            request_structure   = self.atualWs.get('request')

            data_parsed  = self.parser(request, request_structure)

            self.dados_requisicao = request
            
            self.handle_send(data_parsed)
            
    def beforeSend_cliente(self, data):
        return
    
    # Tratamento do retorno da criação de pedidos
    def handle_output_cliente(self, data):
        response = json.loads(self.gamarra_request.req.text) if self.gamarra_request.req.status_code in [200, 400]  else None
        status = ""
        msg_status = ""

        if response == None:
            status = "ER"
            msg_status == "Houve um erro de comunicação, verificar tokens e conexão"

        if not response == None:
            status = "OK" if response['status'] == "sucesso" else "ER"
            msg_status = response['obs']

        saida = "{status}|{msg_status}".format(
            status=status,
            msg_status=msg_status,
        )

        self.write_file(saida, self.saida_cobol, 'w+', encoding='ISO-8859-1')
       
        return 
    
    # ----------------------------------------------------------------- #
        
    def custom_flag_status(self, value, key):
        return "OK" if not value else "ER"
    
    def convert_to_boolean(self, value):
        return True if value == "S" else False
        
        
    
        
