def reprints(reprint_type):
    request_id = ''
    if reprint_type == 'registration':
        registration_no = request.args['registration_no']
        registration_date = request.args['registration_date']
        url = app.config['LAND_CHARGES_URI'] + '/request_details?reprint_type=' + reprint_type
        url += '&registration_no=' + registration_no + '&registration_date=' + registration_date
        response = requests.get(url, headers=get_headers())
        data = json.loads(response.content.decode('utf-8'))
        if "request_id" not in data:
            return "invalid request_id for " + registration_no + ' ' + registration_date
        request_id = data['request_id']
    elif reprint_type == 'search':
        request_id = request.args['request_id']
    if not request_id:
        datetime.strptime(registration_date, '%Y-%m-%d')
        formatted_registration_date = datetime.strptime(registration_date, '%Y-%m-%d').strftime('%d/%m/%Y')
        err = "Could not find request for {} of {}.".format(registration_no, formatted_registration_date)
        logging.error(format_message(err))
        return Response(err, status=400)
    logging.audit(format_message("Request reprint for %s"), request_id)
    # for the time being call reprint on result-generate. this probably needs moving into casework-api
    url = app.config['RESULT_GENERATE_URI'] + '/reprints?request=' + str(request_id)
    response = requests.get(url, headers=get_headers())
    if response.headers['content-type'] == 'application/pdf':
        return send_file(BytesIO(response.content), as_attachment=False, attachment_filename='reprint.pdf',
                         mimetype='application/pdf')
    else:
        err = "An error occured {}.".format(response.text)
        logging.error(format_message(err))
        return Response(err, status=405)
def load_results():
    logging.debug("Calling load results")
    if not app.config['ALLOW_DEV_ROUTES']:
        return Response(status=403)

    if request.headers['Content-Type'] != "application/json":
        logging.error('Content-Type is not JSON')
        return Response(status=415)
    json_data = request.get_json(force=True)
    # go and get some genuine landcharges.request.ids to feed into the results table
    id_count = str(len(json_data))
    response = requests.get(app.config['LAND_CHARGES_URI'] + '/request_ids/' + id_count,
                            headers=get_headers())
    id_list = json.loads(response.content.decode('utf-8'))
    if id_list is None:
        print("no ids retrieved from the land charges uri, run casework-api/data/setup.rb after reset-data")
        return Response(status=200)
    try:
        ctr = 0
        for item in json_data:
            insert_result(id_list[ctr]['request_id'],  item['res_type'])
            ctr += 1
    except:
        raise
    return Response(status=200)
def get_searches():
    logging.audit(format_message("Search reprints"))
    search_data = request.data
    response = requests.post(app.config['LAND_CHARGES_URI'] + '/request_search_details', data=search_data,
                             headers=get_headers({'Content-Type': 'application/json'}))
    data = json.loads(response.content.decode('utf-8'))
    return Response(json.dumps(data), status=200, mimetype='application/json')
def get_counties_list():
    params = ""
    if 'welsh' in request.args:
        if request.args['welsh'] == "yes":
            params = "?welsh=yes"
    else:
        params = "?welsh=no"

    url = app.config['LAND_CHARGES_URI'] + '/counties' + params
    data = requests.get(url, headers=get_headers())
    return Response(data, status=200, mimetype='application/json')
def get_office_copy():
    logging.audit("Retrieve office copy")
    class_of_charge = request.args['class']
    reg_no = request.args['reg_no']
    date = request.args['date']
    uri = app.config['LAND_CHARGES_URI'] + '/office_copy' + '?class=' + class_of_charge + '&reg_no=' + reg_no + \
        '&date=' + date
    response = requests.get(uri, headers=get_headers({'Content-Type': 'application/json'}))
    logging.info('GET {} -- {}'.format(uri, response.text))
    data = json.loads(response.text)
    contents, file_name = create_document_only(data, app.config)
    response = send_file(BytesIO(contents), as_attachment=True, attachment_filename=file_name)
    return response
def get__originals():
    data = request.get_json(force=True)
    logging.debug(json.dumps(data))

    date = data['date']
    number = data['number']
    url = app.config['LAND_CHARGES_URI'] + '/registrations/' + date + '/' + number
    response = requests.get(url, headers=get_headers())
    if response.status_code == 200:
        result = (json.loads(response.text))
    else:
        return Response(json.dumps(response.text), status=response.status_code, mimetype='application/json')

    return Response(json.dumps(result), status=response.status_code, mimetype='application/json')
def save_request_fee(id, fee):
    assert (fee is not None and fee != ''), "Fee is missing"

    # Add transaction fee to the associated request
    url = app.config['LAND_CHARGES_URI'] + '/request/' + id + "/" + fee
    response = requests.put(url, headers=get_headers())
    if response.status_code != 200:
        err = 'Failed to store fee against request ' + id + '. Error code:' \
              + str(response.status_code)

        logging.error(format_message(err))
        raise RuntimeError(err)

    return Response(status=response.status_code, mimetype='application/json')
def insert_complex_name(name, number):
    logging.debug("Complex insert")
    today = datetime.now().strftime('%Y-%m-%d')
    data = {"amend": " ",
            "date": today,
            "number": number,
            "source": " ",
            "uid": " ",  # TODO: ensure this is being passed in
            "name": name
            }

    if 'X-LC-Username' in request.headers:
        data['uid'] = request.headers['X-LC-Username']

    uri = app.config['LEGACY_ADAPTER_URI'] + '/complex_names'
    response = requests.post(uri, data=json.dumps(data), headers=get_headers({'Content-Type': 'application/json'}))
    logging.info('POST {} -- {}'.format(uri, response))
    result = {'response': response.text}
    return Response(json.dumps(result), status=response.status_code, mimetype='application/json')
def get_translated_county(county_name):

    url = app.config['LAND_CHARGES_URI'] + '/county/' + county_name
    data = requests.get(url, headers=get_headers())
    return Response(data, status=200, mimetype='application/json')
def post_search():
    data = request.get_json(force=True)

    logging.debug(json.dumps(data))
    logging.audit("Submit search")

    today = datetime.now().strftime('%Y-%m-%d')
    date_uri = app.config['LEGACY_ADAPTER_URI'] + '/dates/' + today
    date_response = requests.get(date_uri, headers=get_headers())

    if date_response.status_code != 200:
        raise CaseworkAPIError(json.dumps({
            "message": "Unexpected response from legacy_adapter/dates: " + str(date_response.status_code),
            "response": date_response.text
        }))

    # call legacy_adapter to retrieve the next search number
    url = app.config['LEGACY_ADAPTER_URI'] + '/search_number'
    response = requests.get(url, headers=get_headers())
    if response.status_code == 200:
        cert_no = response.text
    else:
        err = 'Failed to call search_number. Error code: {}'.format(str(response.status_code))
        logging.error(format_message(err))
        raise CaseworkAPIError(json.dumps({
            "message": err,
            "response": response.text
        }))

    date_info = date_response.json()
    data['expiry_date'] = date_info['search_expires']
    data['search_date'] = date_info['prev_working']
    data['cert_no'] = cert_no

    uri = app.config['LAND_CHARGES_URI'] + '/searches'
    response = requests.post(uri, data=json.dumps(data), headers=get_headers({'Content-Type': 'application/json'}))
    if response.status_code != 200:
        raise CaseworkAPIError(json.dumps(response.text))

    logging.info('POST {} -- {}'.format(uri, response.text))

    # store result
    response_data = response.json()
    logging.debug(json.dumps(response_data))
    cursor = connect(cursor_factory=psycopg2.extras.DictCursor)
    try:
        # process fee info
        if data['fee_details']['type'] == 'wf' or data['fee_details']['type'] == 'nf':
            save_request_fee(str(response_data[0]), str(0))
        else:
            # build the fee details to pass to legacy_adapter
            build_fee_data(data, response_data, data['fee_details'], 'search')
        store_image_for_later(cursor, data['document_id'], None, None, response_data[0])
        complete(cursor)
    except:
        rollback(cursor)
        raise

    cursor = connect()
    for req_id in response_data:
        uri = app.config['LAND_CHARGES_URI'] + '/search_type/' + str(req_id)
        response = requests.get(uri, headers=get_headers())
        resp_data = response.json()
        res_type = resp_data['search_type']
        insert_result_row(cursor, req_id, res_type)
    complete(cursor)
    return Response(response.text, status=response.status_code, mimetype='application/json')
def court_ref_existence_check(ref):
    logging.debug("Court existence checking")

    url = app.config['LAND_CHARGES_URI'] + '/court_check/' + ref
    response = requests.get(url, headers=get_headers())
    return Response(response.text, status=response.status_code, mimetype='application/json')
def get_complex_names_post():
    data = request.get_json(force=True)
    uri = app.config['LEGACY_ADAPTER_URI'] + '/complex_names/search'
    response = requests.post(uri, data=json.dumps(data), headers=get_headers({'Content-Type': 'application/json'}))
    logging.info('POST {} -- {}'.format(uri, response))
    return Response(response.text, status=response.status_code, mimetype='application/json')
def get_complex_names(name):
    uri = app.config['LEGACY_ADAPTER_URI'] + '/complex_names/' + name
    response = requests.get(uri, headers=get_headers())
    logging.info('GET {} -- {}'.format(uri, response))
    return Response(response.text, status=200, mimetype='application/json')
def get_keyholder(key_number):
    logging.audit(format_message("Get keyholder details"))
    uri = app.config['LEGACY_ADAPTER_URI'] + '/keyholders/' + key_number
    response = requests.get(uri, headers=get_headers())
    return Response(response.text, status=response.status_code, mimetype='application/json')
def validate_county_council(county_name):
    url = app.config['LAND_CHARGES_URI'] + '/county_council/' + county_name
    data = requests.get(url, headers=get_headers())
    return Response(data, status=data.status_code, mimetype='application/json')
def get_next_date_for_registration(date):
    url = app.config['LEGACY_ADAPTER_URI'] + '/dates/' + date
    response = requests.get(url, headers=get_headers())
    data = response.json()
    return Response(json.dumps({'next_working': data['next_working'], 'is_working': data['is_working']}), status=200, mimetype='application/json')
def get_multi_reg_check(reg_date, reg_no):
    logging.audit(format_message("Check multiple registration for %s %s"), reg_no, reg_date)
    url = app.config['LAND_CHARGES_URI'] + '/multi_reg_check/' + reg_date + "/" + reg_no
    data = requests.get(url, headers=get_headers())
    return Response(data, status=200, mimetype='application/json')
def build_fee_data(data, appn, fee_details, action):
    if action == 'complete':
        fee = {'transaction_code': 'RN',
               'key_number': data['key_number'],
               'reference': data['application_ref'],
               'class_of_charge': data['lc_register_details']['class']}
        reg_type = 'new_registrations'
    elif action == 'rectify':
        fee = {'transaction_code': 'RN',
               'key_number': data['applicant']['key_number'],
               'reference': data['applicant']['reference'],
               'class_of_charge': data['class_of_charge']}
        reg_type = 'new_registrations'
    elif action == 'renewal':
        fee = {'transaction_code': 'RN',
               'key_number': data['applicant']['key_number'],
               'reference': data['applicant']['reference'],
               'class_of_charge': data['class_of_charge']}
        reg_type = 'new_registrations'
    elif action == 'cancel':
        fee = {'transaction_code': 'CN',
               'key_number': data['applicant']['key_number'],
               'reference': data['applicant']['reference']}
        reg_type = 'cancellations'
        date = data['registration']['date']
        number = data['registration_no']
        url = app.config['LAND_CHARGES_URI'] + '/registrations/' + date + '/' + number
        response = requests.get(url, headers=get_headers())
        if response.status_code == 200:
            result = (json.loads(response.text))
            fee['class_of_charge'] = result['class_of_charge']
        else:
            err = "Failed to get registration {} of {}. Code: {}".format(
                number, date, response.status_code
            )
            logging.error(format_message(err))
            raise CaseworkAPIError(json.dumps({
                "message": err,
                "response": response.text
            }))

    elif action == 'search':
        if fee_details['delivery'] == 'Postal':
            transaction_code = 'PS'
        else:
            transaction_code = 'XS'

        fee = {'transaction_code': transaction_code,
               'key_number': data['customer']['key_number'],
               'reference': data['customer']['reference'],
               'class_of_charge': ' ',
               'method_of_payment': fee_details['type']}

        fee_data = {'fee_info': fee,
                    'reg_no': ' ',
                    'appn_no': data['cert_no'],
                    'fee_factor': fee_details['fee_factor']}

        # call legacy_adapter to process fee for search and return
        logging.debug("fee information" + json.dumps(fee_data))
        url = app.config['LEGACY_ADAPTER_URI'] + '/fee_process'
        response = requests.post(url, data=json.dumps(fee_data), headers=get_headers())
        if response.status_code == 200:
            fee = response.text
            save_request_fee(str(appn[0]), fee)
            return response.status_code
        else:
            err = "Failed to call fee_process for {}. Code: {}".format(
                data["cert_no"], response.status_code
            )

            logging.error(format_message(err))
            raise CaseworkAPIError(json.dumps({
                "message": err,
                "response": response.text
            }))

    else:
        err = "The fee action is incorrect: {}".format(action)
        logging.error(format_message(err))
        raise CaseworkAPIError(json.dumps({
            "message": err
        }))

        # call legacy_adapter for each registration number
    if 'priority_notices' in appn:
        reg_type = 'priority_notices'

    fee['method_of_payment'] = fee_details['type']

    fee_data = {'fee_info': fee}

    print(appn[reg_type])
    if action == 'cancel':
        fee_data['reg_no'] = number
        fee_data['appn_no'] = str(appn[reg_type][0]['number'])
    else:
        fee_data['reg_no'] = str(appn[reg_type][0]['number'])
        fee_data['appn_no'] = str(appn[reg_type][0]['number'])
    fee_data['fee_factor'] = fee_details['fee_factor']
    logging.debug("fee information " + json.dumps(fee_data))
    url = app.config['LEGACY_ADAPTER_URI'] + '/fee_process'
    response = requests.post(url, data=json.dumps(fee_data), headers=get_headers())
    if response.status_code != 200:
        err = "Failed to call fee_process for {}. Code: {}".format(
            fee_data['appn_no'], response.status_code
        )

        logging.error(format_message(err))
        raise CaseworkAPIError(json.dumps({
            "message": err
        }))
    else:
        fee = response.text
        save_request_fee(str(appn['request_id']), fee)

    return