from math import exp, log


from django.shortcuts import render
from django.views.generic import TemplateView

from scipy import stats

import numpy as np


from .forms import *

# Create your views here.

diameter     = [12.5, 15.0, 17.5, 20.0, 22.5, 25.0, 27.5, 30.0, 32.5]
volume       = [1.02, 1.77, 2.81, 4.19, 5.96, 8.18, 10.9, 14.1, 18.0]

# Flickinger, John C., et al. "Dose selection in stereotactic radiosurgery." Radiosurgery and Pathological Fundamentals 20 (2007): 28-42.
# https://doi.org/10.1159/000100093
Kjellberg    = [27.5, 25.0, 22.5, 20.0, 18.7, 17.5, 16.5, 15.0, 14.0]
ILF          = [34.0, 29.0, 23.0, 18.0, 16.5, 14.5, 13.5, 13.0, 12.5]
RTOG         = [24.0, 24.0, 24.0, 24.0, 18.0, 18.0, 18.0, 18.0, 15.0]

NCT02353000  = [24.0, 21.0, 21.0, 21.0, 21.0, 21.0, 18.0, 18.0, 15.0] # https://doi.org/10.1186/s12885-017-3494-z

# http://www.aboutcancer.com/gk_doses.htm
Pit          = [20.0, 20.0, 20.0, 20.0, 16.0, 16.0, 15.0, 15.0, 14.0] # U Pitt
Other        = [24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 22.0, 22.0, 16.0] # Other sites (e.g. Cleveland Clinic) Too high?
Karolinska   = [25.0, 25.0, 22.5, 20.0, 20.0, 20.0, 18.0, 18.0, 18.0] # Karolinska Policy on Brain Mets
ACOSOG_Z0300 = [24.0, 24.0, 24.0, 20.0, 20.0, 20.0, 20.0, 18.0, 18.0] # ACOSOG Z0300


def log_regression(func, v):

#    print func

#    dose = map(func, Kjellberg, ILF, RTOG)
#    dose = [func([Kjellberg[i], ILF[i], RTOG[i]]) for i in range(len(volume))]
#    dose = [func([Kjellberg[i], ILF[i], RTOG[i], NCT02353000[i]]) for i in range(len(volume))]

    dose = [func([
        Kjellberg[i],
        ILF[i],
        RTOG[i],

        # NCT02353000[i],

#        Pit[i],
#        Other[i],
#        Karolinska[i],
#        ACOSOG_Z0300[i],

        ]) for i in range(len(volume))]

#    print dose

    logv = list(map(log, volume))
    logd = list(map(log, dose))

#     print(logv)

    gradient, intercept, r_value, p_value, std_err = stats.linregress(logv, logd)
#    print "Gradient and intercept", gradient, intercept
    return exp(log(v) * gradient + intercept)


def solve_d(d1, n, ab = 2.0):
    coeff = [n/ab, n, -d1*(1+d1/ab)]
    d = np.roots(coeff)[1]
    return n*d


def fraction_string(d):
    return (d,
        solve_d(d, 2),
        solve_d(d, 3),
        solve_d(d, 4),
        solve_d(d, 5),
        )


class PresciptionView(TemplateView):
    template_name = 'calculator/prescription.html'

    def get(self, request, *args, **kwargs):
        form = PresciptionForm()
        return render(request,self.template_name, {'form':form})

    def post(self,request):
        form = PresciptionForm(request.POST)
        if form.is_valid():
            v = form.cleaned_data['volume']
            result = {}

            result['min']    = fraction_string(log_regression(min      , v))
            result['mean']   = fraction_string(log_regression(np.mean  , v))
            result['median'] = fraction_string(log_regression(np.median, v))
            result['max']    = fraction_string(log_regression(max      , v))

            form = PresciptionForm()
            #return redirect ('home:home')

        args = {'form': form , 'result': result}
        return render(request, self.template_name, args )

class CIView(TemplateView):
    template_name = 'calculator/ci.html'

    def get(self, request, *args, **kwargs):
        form = CIForm()
        return render(request,self.template_name, {'form':form})

    def post(self,request):
        form = CIForm(request.POST)
        if form.is_valid():
            Px       = form.cleaned_data['Px']
            Coverage = form.cleaned_data['Coverage']
            TV       = form.cleaned_data['TV']
            PIV      = form.cleaned_data['PIV']
            result = {}

            TVPIV = Coverage*TV/100
            result['TVPIV'] = Coverage*TV/100
            result['CI']    = PIV/TVPIV
            result['nCI']   = (PIV/TVPIV)*(TV/TVPIV)

            form = CIForm()
            #return redirect ('home:home')

        args = {'form': form , 'result': result}
        return render(request, self.template_name, args )        