#!/usr/bin/python3

import json
from libs.common import api_call, HEADERS
from libs.config import CONFIG


def try_dissociate_user_from_line(line_id):
    user_ids = _get_users_of_line(line_id)
    if user_ids:
        user_id = user_ids[0]
        _dissociate_user_from_line(user_id, line_id)
        return user_id
    

def delete_user(user_id):
    print(f"Deleting user {user_id}")
    url = f"{CONFIG['url_prefix']}/users/{user_id}"
    api_call("DELETE", url, HEADERS)


def _get_users_of_line(line_id):
    print(f"Fetching all users of line {line_id}")
    url = f"{CONFIG['url_prefix']}/lines/{line_id}/users"
    response = json.loads(api_call("GET", url, HEADERS).text)
    users = [user['user_id'] for user in response['items']]
    return users


def _dissociate_user_from_line(user_id, line_id):
    print(f"Removing user {user_id} from line {line_id}")
    url = f"{CONFIG['url_prefix']}/users/{user_id}/lines/{line_id}"
    api_call("DELETE", url, HEADERS)


