#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
from astropy.modeling import Fittable1DModel, fitting
from collections import OrderedDict

def fit_sasmodel(model, q, data, method='LevMarLSQFitter', **kwargs):
    """
    Fit an XicamSASModle using astropy.ftting routines.

    Parameters
    ----------
    model : XicamSASModel
        Model generated by the factroy method
    q     : np.ndarray
        q-range for the fitting
    data  : np.ndarray
        SAXS spectra over input q-range
    method: str
        one of [LinearLSQFitter, LevMarLSQFitter, SLSQPLSQFitter]
    kwargs: dict
        astropy fitting related key: arguments

    Returns
    -------
        Fitted parameters, values
    """

    # supported fitters
    fitters = OrderedDict({
        'LinearLSQFitter': fitting.LinearLSQFitter,
        'LevMarLSQFitter': fitting.LevMarLSQFitter,
        'SLSQPLSQFitter' : fitting.SLSQPLSQFitter
        })

    # sanity checks
    if not isinstance(model, Fittable1DModel):
        raise TypeError('Input model must be astropy Fittable1DModel or subtype')

    if not np.shape(q) == np.shape(data):
        raise ValueError('q and I must be of same shape')

    if not method in fitters:
        raise ValueError('Unsupported fitting methods')

    # give it your best shot. maybe!
    fit_t = fitters[method]()
    g = fit_t(model, q, data, **kwargs)
    return g.parameters, g(q)
