import numpy as np
import logging

from openflexure_microscope.devel import (
    MicroscopeViewPlugin,
    JsonResponse,
    request,
    jsonify,
    taskify,
    abort,
)


class MeasureSharpnessAPI(MicroscopeViewPlugin):
    def post(self):
        payload = JsonResponse(request)
        return jsonify({"sharpness": self.plugin.measure_sharpness()})


class AutofocusAPI(MicroscopeViewPlugin):
    """
    Run a standard autofocus
    """

    def post(self):
        payload = JsonResponse(request)

        # Figure out the range of z values to use
        dz = payload.param("dz", default=np.linspace(-300, 300, 7), convert=np.array)

        if self.microscope.has_real_stage():
            logging.info("Running autofocus...")
            task = taskify(self.plugin.autofocus)(dz)

            # return a handle on the autofocus task
            return jsonify(task.state), 201

        else:
            abort(503, "No stage connected. Unable to autofocus.")


class FastAutofocusAPI(MicroscopeViewPlugin):
    """
    Run a fast autofocus
    """

    def post(self):
        payload = JsonResponse(request)

        # Figure out the parameters to use
        dz = payload.param("dz", default=2000, convert=int)
        backlash = payload.param("backlash", default=0, convert=int)
        if backlash < 0:
            backlash = 0

        if self.microscope.has_real_stage():
            logging.info("Running autofocus...")
            task = taskify(self.plugin.fast_autofocus)(dz, backlash=backlash)

            # return a handle on the autofocus task
            return jsonify(task.state), 201

        else:
            abort(503, "No stage connected. Unable to autofocus.")
