import json

import requests

import config
from classes.Answer import Answer
from classes.Order import Order
from classes.OrderTicket import OrderTicket
from classes.Ticket import Ticket



# Функция обращения к апи и получение токена
def requestGetToken(login, password, url) -> str:
    login = "79999999999"
    password = "12345"
    # login = "11111111111"
    # password = "Sharix!"
    # url = "https://user.sharix-app.org/auth/token/login/"
    data = {
        "password": password,
        "phone_number": login
    }
    response = requests.post(url, json=data)
    result = response.json()
    return result['auth_token']


# Функция обращения к апи и получение токена


def msg_to_text(jsonstring):
    jsonObj = json.loads(jsonstring)
    u = jsonObj
    return u


def createUser(username, phone, password, url) -> str:
    data = {
        "username": username,
        "phone_number": phone,
        "password": password
    }
    response = requests.post(url, json=data)
    result = response.json()
    return result


# Функция обращения к апи и получение списка пользователей


def requestGetListUser():
    auth_token = requestGetToken()
    print(auth_token)
    headers = {'Authorization': f'Token {auth_token}'}
    url = 'https://user.sharix-app.org/platform/api/sharix-users/'
    response = requests.get(url, headers=headers)
    print(response)
    print(response.json())


# def requestGetList(auth_token, url):
#     headers = {'Authorization': f'Token {auth_token}'}
#     response = requests.get(url, headers=headers)
#     #response = requests.get(config.API_URL+"/dbsynce/api/orders/", headers=headers)
#     ordertext=response.json()
#     startlist = []

#     if not ordertext:
#         print("Empty array")
#     else:
#         for i in ordertext:
#             print (i, "PROCESSING")
#             try:
#                 orderticket = OrderTicket(**i)
#                 print(i, "ORDER ", orderticket)
#                 startlist.append(orderticket)
#             except Exception as ex:
#                 print(ex)
#     print (startlist)
#     return startlist


def requestGetList(auth_token, url):
    headers = {'Authorization': f'Token {auth_token}'}
    response = requests.get(url, headers=headers)
    # response = requests.get(config.API_URL+"/dbsynce/api/orders/", headers=headers)
    ordertext = response.json()
    startlist = []

    if not ordertext:
        print("Empty array")
    else:
        for i in ordertext:
            print(i, "PROCESSING")
            try:
                order = Order(**i)
                print(i, "ORDER ", order)
                startlist.append(order)
            except Exception as ex:
                print(ex)
    print(startlist)
    return startlist


def requestGetTicket(auth_token, url):
    headers = {'Authorization': f'Token {auth_token}'}
    response = requests.get(url, headers=headers)

    # response = requests.get(config.API_URL+"/dbsynce/api/orders/", headers=headers)
    tickettext = response.json()
    startlist = []
    if not tickettext:
        print("Empty array")
    else:
        for i in tickettext:
            try:
                ticket = Ticket(**i)
                startlist.append(ticket)
            except Exception as ex:
                print(ex)
    print(startlist)
    return startlist


def requestPatchTicketUser(token, url, data):
    headers = {'Authorization': f'Token {token}'}
    response = requests.patch(url, json=data, headers=headers)
    return response


def change_groups(auth_token, url, group):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Token {auth_token}'
    }
    response = requests.get(url, headers=headers)
    user_data = response.json()
    current_groups = user_data.get('groups', [])
    updated_groups = list(set([group] + current_groups))
    data = {'groups': updated_groups}
    print(data)
    response = requests.put(url, json=data, headers=headers)
    print(url)
    print(user_data)
    return response


def change_status_company(auth_token, url, id_metaservice):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Token {auth_token}'
    }
    response = requests.get(url, headers=headers)
    user_data = response.json()
    print(user_data)
    current_metaservice = user_data.get('id_metaservice', [])
    repsonse = requests.put(config.API_URL + f"dbsynce/api/company/{id_metaservice}", json=data, headers=headers)
    return response


def to_answer(jsonstring):
    json_answer = json.loads(jsonstring)
    print(json_answer)
    u = Answer(**json_answer)
    return u


def change_to_task(localtask, token):
    headers = {
        'Authorization': f'Token {token}',
        'Content-Type': 'application/json'  # Установка заголовка Content-Type
    }
    data = json.dumps(localtask.__dict__)
    response = requests.patch(config.API_URL + f"/dbsynce/api/orders/{localtask.id}/", headers=headers, data=data)
    return response
