import math
import numpy as np
import os
from scipy.interpolate import interp1d
from numpy import genfromtxt
import time


def scan_range(lambda_mean, res):
    items = os.listdir(".")
    for names in items:
        if names.endswith("parameters_int.txt"):
            filename = names

    ref = np.genfromtxt(filename, delimiter = '\t')

    ref1 = ref[0,:]

    low = ref1[0]
    high = ref1[-1]

    alpha = np.radians(10)
    min_e = 100.0
    min_o = 100.0
    lambda_mean = lambda_mean / 1000

    extra=genfromtxt('Tamosauskas-e.csv', delimiter=',')
    ordinary=genfromtxt('Tamosauskas-o.csv', delimiter=',')

    wave_extra=extra[:,0]
    n_extra=extra[:,1]
    f1=interp1d(wave_extra, n_extra, kind="linear")
    n_e=f1(lambda_mean)

    wave_ordinary=ordinary[:,0]
    n_ordinary=ordinary[:,1]
    f2=interp1d(wave_ordinary, n_ordinary, kind="linear")
    n_o = f2(lambda_mean)


    delta_n = n_e-n_o

    max_excursion = lambda_mean ** 2 / (delta_n * res * math.sin(alpha))  # in [mm]

    start = max_excursion
    end = -max_excursion

    if start<low:
        start=low
    if end>high:
        end=high

    return start, end
