import concurrent.futures
import os
import datetime
import requests
from threading import Lock

from flask import Blueprint

from common.status import HTTP_200_OK
from flask_jwt_extended import jwt_required

from ressources.blueprint.organilogStatus import Status

from common.status import HTTP_500_INTERNAL_SERVER_ERROR

organilog_ticket_blueprint = Blueprint('organlog_ticket', __name__)

verrou = Lock()

customer_id = os.environ.get('MEDIAN_ORGANILOG_CLIENT', '')
customer_account = os.environ.get('MEDIAN_ORGANILOG_ACCOUNT', '')
customer_token = os.environ.get('MEDIAN_ORGANILOG_TOKEN', '')


def organilog_result(num_page):
    last = datetime.datetime.now() - datetime.timedelta(days=30)
    try:
        r = requests.post('https://sync.organilog.com/api/v3/issue/read_all.php',
                          json={
                              "account": customer_account,
                              "token": customer_token,
                              "last_datetime": last.strftime('%Y-%m-%d 00:00'),  # "2022-10-07 00:00",
                              "page_nbr": num_page,
                              "order_by": "id",
                              "order_sort": "asc",
                              "title": ""})
        return r.json()
    except requests.exceptions.RequestException as e:
        return {'REQUEST': e}


def get_ticket_page(obj):
    res = organilog_result(obj['nb'])
    list_res = res['results']
    list_current = list(filter(lambda f: (f['fk_client_id'] == customer_id) and (f['status'] != Status.REJECTED.value),
                               list_res))

    verrou.acquire()
    obj['issue']['list'].extend(list_current)
    verrou.release()


@organilog_ticket_blueprint.route('list', methods=['GET'])
@jwt_required()
def get_tickets_list():
    issue = {'list': []}

    if customer_id != '' and customer_token != '' and customer_account != '':
        res = organilog_result(1)

        if 'ERROR' in res:
            return {'message': 'dashboard.ticket.error.identification'}, HTTP_500_INTERNAL_SERVER_ERROR
        elif 'REQUEST' in res:
            return {'message': 'dashboard.ticket.error.request'}, HTTP_500_INTERNAL_SERVER_ERROR

        nb_pages = res.get('count_pages', 0)
        pages = []
        while nb_pages > 0:
            obj = {'nb': nb_pages,
                   'issue': issue}
            pages.append(obj)
            nb_pages = nb_pages - 1

        with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
            executor.map(get_ticket_page, pages)

    return {'counters': issue}, HTTP_200_OK
