import os
import requests
import time


API_KEY = 'acc_xxxxxxxxxxxxxxx'
API_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

API_ENDPOINT = 'https://api.imagga.com/v2'
CATEGORIZER = 'general_v3'  # The default general purpose categorizer
INDEX_NAME = 'similarity_tutorial_v1'

categorizer_endpoint = '%s/categories/%s' % (API_ENDPOINT, CATEGORIZER)
index_endpoint = ('%s/similar-images/categories/%s/%s' %
                  (API_ENDPOINT, CATEGORIZER, INDEX_NAME))
tickets_endpoint = '%s/tickets' % API_ENDPOINT


def feed_image(image_path):
    file_name = os.path.basename(image_path)
    image_name, extension = os.path.splitext(file_name)

    # Make the API call
    response = requests.post(
        categorizer_endpoint,
        auth=(API_KEY, API_SECRET),
        files={'image': open(image_path, 'rb')},
        params={'save_id': image_name, 'save_index': INDEX_NAME})

    # Check for errors
    try:
        status = response.json()['status']
        if status['type'] != 'success':
            print('API reported error:', status['text'])
            return False
    except Exception as e:
        print('Exception occured during handling the feeding response')
        print(e)
        return False

    return True


def train_index():
    ticket_id = ''

    # Make the API call
    response = requests.put(index_endpoint, auth=(API_KEY, API_SECRET))

    # Get the completion ticket
    try:
        ticket_id = response.json()['result']['ticket_id']
    except Exception as e:
        print('Exception occured when processing the train call response')
        print(e, response.content)

    return ticket_id


def is_resolved(ticket_id):
    resolved = False

    # Make the API call
    response = requests.get(
        '%s/%s' % (tickets_endpoint, ticket_id), auth=(API_KEY, API_SECRET))

    # Check for errors
    try:
        resolved = response.json()['result']['is_final']
    except Exception as e:
        print('Exception occured during the ticket status check')
        print(e)

    return resolved


def main():
    # Feed the visual search index with images
    successful_feeds = 0
    failed_feeds = 0

    for image in os.scandir('./index_creation_set'):
        print('At image %s: %s' % (successful_feeds, image.path))

        successful = feed_image(image.path)
        if successful:
            successful_feeds += 1
        else:
            failed_feeds += 1

    # Report
    if not successful_feeds:
        print('No images were fed successfully. Exiting')
        return

    print(
        '%s out of %s images fed successfully' %
        (successful_feeds, successful_feeds + failed_feeds))

    # Train the index
    ticket_id = train_index()

    if not ticket_id:
        print('No ticket id. Exiting')
        return

    # Wait for the training to complete
    time_started = time.time()
    while not is_resolved(ticket_id):
        t_passed = (time.time() - time_started) // 1000
        print(
            'Waiting for training to finish (time elapsed: %.1fs)' % t_passed)

        time.sleep(0.5)

    print('Training done.')


if __name__ == '__main__':
    main()
