import requests
import random
import string
import json
import datetime
import time
import os
from classes.users import Users


# anwer_text = '{"question_chains":[{"id":6145,"questions":[{"id":6559,"question_components":[{"id":18850,"answer":[80634165],"answer_status":null,"end_time":1591866979,"start_time":1591866978},{"id":18851,"answer":{"location":[56.439337,36.557897]},"answer_status":null,"start_time":1591866873,"end_time":1591867165},{"id":18852,"answer":"1","answer_status":null,"start_time":1591867063,"end_time":1591867063}]}]},{"id":6147,"questions":[{"id":6561,"question_components":[{"id":18856,"answer":77,"answer_status":null,"end_time":1591867067,"start_time":1591867067},{"id":18857,"answer":[80639138],"answer_status":null,"end_time":1591867186,"start_time":1591867185}]}]},{"id":6147,"questions":[{"id":6561,"question_components":[{"id":18856,"answer":77,"answer_status":null,"end_time":1591867200,"start_time":1591867200},{"id":18857,"answer":[80639640],"answer_status":null,"end_time":1591867206,"start_time":1591867205}]}]},{"id":6147,"questions":[{"id":6561,"question_components":[{"id":18856,"answer":77,"answer_status":null,"end_time":1591867211,"start_time":1591867211},{"id":18857,"answer":[80640010],"answer_status":null,"end_time":1591867220,"start_time":1591867219}]}]},{"id":6147,"questions":[{"id":6561,"question_components":[{"id":18856,"answer":77,"answer_status":null,"end_time":1591867223,"start_time":1591867223},{"id":18857,"answer":[80640333],"answer_status":null,"end_time":1591867233,"start_time":1591867232}]}]}]}'







def get_questions(id_task, session, headers):
    url = 'https://knd.mosreg.ru//api/v1/executions/'+str(id_task)+'/questions'
    questions = session.get(url, headers=headers)
    json_quest = questions.json()
    return json_quest['selected_chains']



def send_image(session, headers, url, photo):
    """Отправляем фото на сервер. Сервер должен вернуть id и url."""
    files = {
        'image': (photo[-5:], open(photo, 'rb')),
    }
    # print(files)
    img = session.post('https://knd.mosreg.ru//api/v1/executions/'+str(url)+'/images', headers=headers, files=files)
    if img.status_code == 200:
        return img.json()
    else:
        print(f"Не удалось загрузить фото на сервер по заданию {url}, статус ошибки {img.status_code}! Завершите его вручную!")


def complete_task(session, headers, task, address):
    photos = get_photo(address, headers['uid'])
    if len(photos) > 0:
        photos.sort()
    print(task['id'])
    id_task = task['id']
    questions = get_questions(id_task, session, headers)
    data = []
    for answers in questions:
        answer_chain = {
            'id': answers['id'],
            'questions': []#answers['questions']
        }
        if answer_chain['id'] == 6146:  # Цепочка без ответов
            continue
        for components in answers['questions']:
            comp = []
            q_c = {
                'id': components['id'],
                'question_components': []
            }
            if q_c['id'] == 6560:  # Вопрос без ответа
                continue
            comp.append(q_c)
        answer_chain.update({'questions': comp})
        data.append(answer_chain)
    if len(data) == len(photos):
        for chain in data:
            for item in chain['questions']:
                if len(data) == len(photos):
                    img = send_image(session, headers, task['id'], photos.pop(0))
                    first = {"id": 18850, "answer": [img['id']], 'answer_status': None, 'start_time': int(time.time())}
                    time.sleep(2)
                    first.update({'end_time': int(time.time())})
                    second = {"id": 18851, "answer": {"location": task['coord']}, 'answer_status': None, 'start_time': int(time.time())}
                    time.sleep(2)
                    second.update({'end_time': int(time.time())})
                    item['question_components'].append(first)
                    item['question_components'].append(second)
                else:
                    img = send_image(session, headers, task['id'], photos.pop(0))
                    first = {"id": 18856, "answer": 77, 'answer_status': None, 'start_time': int(time.time())}
                    time.sleep(2)
                    first.update({'end_time': int(time.time())})
                    second = {"id": 18857, "answer": [img['id']], 'answer_status': None, 'start_time': int(time.time())}
                    time.sleep(2)
                    second.update({'end_time': int(time.time())})
                    item['question_components'].append(first)
                    item['question_components'].append(second)
        ans = {"question_chains": data}
        # print(ans)
        session_t = session
        session_t.headers.update(
            {
                'referer': 'https://knd.mosreg.ru/executions'+str(task['id'])+'/solve',
                'x-platform': 'wb',
                'accept': '*/*'
             }
        )
        complete = session_t.post('https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/answers', headers=headers, json=ans)
        if complete.status_code == 200:
            print(f'Задание по адресу {address} выполнено успешно!')
        else:
            print(f'Задание по адресу {address} не выполненно! Статус ошибки {complete.status_code}')
    else:
        print(f"Несоответствие количества вопросов и количества фотографий по адресу: {address}")
#    send_execution(task,session, headers)


def get_photo(address, email):
    photos = []
    month = datetime.datetime.now().month
    main_path = os.path.join(os.path.abspath('.'), 'data', email, str(month), address)
    if not os.path.exists(main_path):
        return photos
    else:
        for images in os.listdir(main_path):
            if images.endswith(".jpg") or images.endswith(".jpeg"):
                photos.append(main_path + '/' + images)
        return photos


def get_addresses(email):
    addresses = []
    month = datetime.datetime.now().month
    main_path = os.path.join(os.path.abspath('.'), 'data')
    path = os.walk(os.path.join(main_path, email, str(month)))
    if not os.path.exists(os.path.join(main_path, email, str(month))):
        return f"Не найдена папка с месяцем у пользователя {email}! Проверьте структуру каталога!"
    for d, dirs, files in path:
        addresses.append(dirs)
    if len(addresses[0]) > 0:
        return addresses[0]
    else:
        return f"Ни одного адреса для пользователя {email} не найдено! Добавьте фото и запустите программу снова!"


def assign_task(session, headers, task, address):
#    complete_task(session, headers, task, address)
    # DON'T START PROGRAM!!!!
    url = 'https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/assign'
    task_assign = session.put(url, headers=headers)
    if task_assign.status_code == 200:
        print(f'Получили задани по адресу: {address}')
        complete_task(session, headers, task, address)
    else:
        print(f"Не смогли получить задание {address} {task['id']}!")


def get_task(session, headers):
    """Получаем все доступные задания. Если в переменную search добавить адрес,
    то будет искать этот адрес. Он попадет в
    json_tasks['executions_available'],
    так что надо понять откуда берем задания. Отсюда можно возвращать
    все параметры задания:
    1 координаты
    2 адрес
    3 подъезд
    4 id_задания"""
    # Получаем адреса
    addresses = get_addresses(headers['uid'])
    # Если адреса получили
    if isinstance(addresses, list):
        session_t = session
        session_t.headers.update(
            {'referer': 'https://knd.mosreg.ru/executions',
             'x-platform': 'wb',
             'accept': '*/*'
             }
        )
        for address in addresses:
            # need split enterance from address
            search = address[:-4]
            # print(search)
            data = {'search': search}
            tasks = session_t.post('https://knd.mosreg.ru//api/v1/executions',
                                   headers=headers,
                                   data=data
                                   )
            json_tasks = tasks.json()
            get_t = False
            # Если есть доступное задание с таким адресом
            if len(json_tasks['executions_available']) > 0:
                for n in json_tasks['executions_available']:
                    coord = n['coord']
                    enterances = n['tasks']
                    for execution in enterances:
                        address_from_tasks = execution['dimensions'][0].get('entity_value_name')
                        # print(address_from_tasks)
                        # print('Клин г, '+address[:-4])
                        enterance = execution['dimensions'][2].get('entity_value_name')
                        # print(enterance)
                        # print(address[-2])
                        if address_from_tasks == 'Клин г, '+address[:-4] and \
                           enterance[-1] == address[-2]:
                            print(f'Начали выполнение задания по адресу: {address}')
                            task = {
                                'id': execution['execution_id'],
                                'address': execution['dimensions'][0].get('entity_value_name'),
                                'enterance': execution['dimensions'][2].get('entity_value_name'),
                                'coord': coord
                            }
                            # Принимаем задание
                            assign_task(session, headers, task, address)
                            get_t = True
                if not get_t:
                    print(f"Нет доступных заданий для по адресу: {address}!")
            # Если нет задания с таким адресом
            else:
                print(f"Нет доступных заданий для пользователя {headers['uid']} по адресу: {address}")
    # Если адреса не получили выводим ошибку
    else:
        print(addresses)


def main():
    users = Users()
    logins = users.get_passwords()
    if isinstance(logins, list):
        url = 'https://knd.mosreg.ru//api/v1/auth/sign_in'
        for user in logins:
            session = requests.Session()
            login = {
                'email': user['email'],
                'password': user['password']
            }
            response = session.post(url, data=login)
            headers = {
                'client': response.headers.get('client'),
                'Access-token': response.headers.get('Access-token'),
                'uid': response.headers.get('uid'),
            }
            if response.status_code == 200:
                # task = {
                #     'id': 23799105,
                #     'address': 'Решетниково рп, ОПМС-1 проезд, 13',
                #     'enterance': 6,
                #     'coord': [56.442503, 36.5596493]
                # }
                # address = 'Решетниково рп, ОПМС-1 проезд, 13, 6п'
                # assign_task(session, headers, task, address)
                # break
                get_task(session, headers)
            else:
                print(f"Отказ в авторизации для пользователя {user['email']}!")
            time.sleep(1)
    else:
        print(users.get_passwords())


if __name__ == "__main__":
    main()


def random_string(stringLength):
    letters = string.ascii_letters
    digits = string.digits
    return ''.join(random.choice(letters+digits) for i in range(stringLength))
