from distutils.util import strtobool
from flask import Blueprint, current_app, jsonify, Response, request

from inventory_provider.tasks import ims_worker
from inventory_provider.routes import common
from inventory_provider.tasks.common import get_current_redis, get_latch

routes = Blueprint("ims-inventory-data-job-routes", __name__)


@routes.route('/update', methods=['GET', 'POST'])
@common.require_accepts_json
def update_from_ims():
    force = request.args.get('force', default='false', type=str)
    try:
        force = strtobool(force)
    except ValueError:
        force = False

    config = current_app.config['INVENTORY_PROVIDER_CONFIG']
    r = get_current_redis(config)

    if not force:
        latch = get_latch(r)
        if latch and latch['pending']:
            return Response(
                response='an update is already in progress',
                status=503,
                mimetype="text/html")

    phase2_task_id = ims_worker.launch_refresh_cache_all(config)

    r.set('classifier-cache:update-task-id', phase2_task_id.encode('utf-8'))
    return jsonify({'task id': phase2_task_id})