#! /opt/local/bin/python
# -*- coding: utf-8 -*-

# PyNX - Python tools for Nano-structures Crystallography
#   (c) 2017-present : ESRF-European Synchrotron Radiation Facility
#       authors:
#         Vincent Favre-Nicolin, favre@esrf.fr

import timeit
import numpy as np

from .runner import CDIRunner, CDIRunnerException, CDIRunnerScan, default_params as params0
from pynx.cdi import *

helptext_epilog = " \n\nExamples:\n" \
                  " * ``pynx-cdi-id10 --data data.cxi --support circle --support_size 70 " \
                  "--support_threshold 0.25 --detwin --positivity``\n" \
                  " * ``pynx-cdi-id10 --data data.cxi --support circle --support_size 70 " \
                  "--support_threshold 0.25 --detwin --positivity --liveplot " \
                  "--nb_hio 800 --nb_er 100 --verbose 100 --nb_run 100 --nb_run_keep 10``"

params_beamline = {
    'detwin': False,
    'instrument': 'ESRF ID10',
    'mask': ['zero'],
    'nb_raar': 0,
    'nb_hio': 600,
    'nb_er': 200,
    'nb_ml': 0,
    'positivity': True,
    'roi': None,
    'support_type': 'circle',
    'support_size': 50,
    'zero_mask': 0,
}

default_params = params0.copy()
for k, v in params_beamline.items():
    default_params[k] = v


class CDIRunnerScanID10(CDIRunnerScan):
    def __init__(self, params, scan, timings=None):
        super(CDIRunnerScanID10, self).__init__(params, scan, timings=timings)

    def prepare_cdi(self):
        """
        Prepare CDI object from input data.

        :return: nothing. Creates or updates self.cdi object.
        """
        super(CDIRunnerScanID10, self).prepare_cdi()
        # Scale initial object (unnecessary if auto-correlation is used)
        if self.params['support'] != 'auto':
            self.cdi = ScaleObj(method='F', lazy=True) * self.cdi


class CDIRunnerID10(CDIRunner):
    """
    Class to process a series of scans with a series of algorithms, given from the command-line
    """

    def __init__(self, argv, params, *args, **kwargs):
        super().__init__(argv, params)
        self.CDIRunnerScan = CDIRunnerScanID10

    @classmethod
    def make_parser(cls, description=None, script_name="pynx-ptycho-id10", epilog=None, default_par=None):
        if default_par is None:
            default_par = default_params
        if epilog is None:
            epilog = helptext_epilog
        if description is None:
            description = "Script to perform a CDI analysis on data from ID10@ESRF"

        parser = super().make_parser(script_name, description, epilog, default_par)
        return parser

    def check_params_beamline(self):
        """
        Check if self.params includes a minimal set of valid parameters, specific to a beamiline
        Returns: Nothing. Will raise an exception if necessary
        """
        if self.params['data'] is None:
            raise CDIRunnerException('No data provided. Need at least data=..., or a parameters input file')


def make_parser_sphinx():
    """Returns the argparse for sphinx documentation"""
    return CDIRunnerID10.make_parser()
