# -*- coding: utf-8 -*-

import requests
import logging
import hashlib
import json
from odoo import models, fields, api, _
from datetime import datetime, timedelta


_logger = logging.getLogger(__name__)

HEADERS = {
    'X-API-KEY': 'b84f2c33-d9dc-439a-84ff-3deed4b18e10',
    'Content-Type': 'application/json',
}


class ExelyApiConf(models.Model):
    _name = 'exely.api.conf'
    _description = 'Exely Api Conf'

    api_key = fields.Char(string="API Key", required=True)
    api_url = fields.Char(string="API URL", required=True)

    def get_headers(self):
        return [self.api_url, {
            'X-API-KEY': self.api_key,
            'Content-Type': 'application/json',
        }]

    def test_api_connection(self):
        api_conf = self.get_headers()
        try:
            response = requests.get(f"{api_conf[0]}/companies", headers=api_conf[1])
            if response.status_code == 200:
                data = response.json()
                message = _("Connection Test Successful!")
                message_type = 'success'
            else:
                message = _("Connection Test Failed!")
                message_type = 'danger'
        except Exception as e:
            message = _("Connection Test Failed!")
            message_type = 'danger'
            _logger.error(e)

        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'message': message,
                'type': message_type,
                'sticky': False,
            }
        }