import os
import datetime
from smb.SMBConnection import SMBConnection
from dotenv import load_dotenv
from DroneScanner.utils.datas_processing import pack_elems, agregator, send_data, save_data, remote_save_data
from DroneScanner.core.sig_n_medi_collect import Signal, SignalsArray, get_signal_length
from DroneScanner.core.multichannelswitcher import MultiChannel, get_centre_freq

dotenv_path = os.path.join(os.path.dirname(__file__), '../../.env')
if os.path.exists(dotenv_path):
    load_dotenv(dotenv_path)

debug_flag = bool(os.getenv('debug_flag'))
send_to_module_flag = bool(os.getenv('send_to_module_flag'))
save_data_flag = bool(os.getenv('save_data_flag'))
module_name = os.getenv('module_name')
elems_to_save = os.getenv('elems_to_save')
file_types_to_save = os.getenv('file_types_to_save')
localhost = os.getenv('lochost')
localport = os.getenv('locport')
f_step = [*map(float, os.getenv('f_step_1200').split())]
f_bases = [*map(float, os.getenv('f_bases_1200').split())]
f_roofs = [*map(float, os.getenv('f_roofs_1200').split())]

c_freq = as_str(os.getenv(f'c_freq_{freq_suffix}', freq_suffix))path_to_save_medians = os.getenv('path_to_save_medians')
path_to_save_alarms = os.getenv('path_to_save_alarms')
smb_host = os.getenv('smb_host')
smb_port = os.getenv('smb_port')
smb_user = os.getenv('smb_user')
smb_pass = os.getenv('smb_pass')
shared_folder = os.getenv('shared_folder')
the_pc_name = os.getenv('the_pc_name')
remote_pc_name = os.getenv('remote_pc_name')
smb_domain = os.getenv('smb_domain')

elems_to_save = elems_to_save.split(',')
file_types_to_save = file_types_to_save.split(',')

tmp_signal = Signal()
tmp_sigs_array = SignalsArray()
multi_channel = MultiChannel(
    f_step,
    f_bases,
    f_roofs,
    config_tags=[freq_suffix] * len(f_step),
    report_freqs=[c_freq] * len(f_step),
)
f = multi_channel.init_f()
multi_channel.fill_DB()

if debug_flag:
    conn = SMBConnection(smb_user, smb_pass, the_pc_name, remote_pc_name, use_ntlm_v2=True)
    conn.connect(smb_host, 139)
    filelist = conn.listPath(shared_folder, '/')
    print(filelist)


def work(lvl):

    f = multi_channel.get_cur_channel()
    config_tag = multi_channel.get_config_tag(f)
    freq = multi_channel.get_report_freq(f)
    signal_length = get_signal_length(config_tag)
    median, signal, abs_signal = tmp_signal.fill_sig(lvl, signal_length)

    if median != -1:
        try:
            num_chs, circle_buffer = multi_channel.check_f(f)

            #print(f, freq, num_chs, signal_length)
            #print(median)

            cur_channel, sigs_array = tmp_sigs_array.fill_sig_arr(median, num_chs)

            if sigs_array:
                print('Значения на {0}: {1}'.format(freq, sigs_array))
                print('Пороги: ', circle_buffer.get_medians())
                alarm = circle_buffer.check_alarm(sigs_array)

                if alarm:
                    print('----ALARM---- ', freq)
                    multi_channel.db_alarms_zeros(circle_buffer)
                else:
                    circle_buffer.update(sigs_array)

                if send_to_module_flag:
                    send_data(agregator(freq, alarm), localhost, localport)

                if save_data_flag:
                    if not circle_buffer.check_init() and circle_buffer.current_column - 1 == 0:
                        save_data(path_to_save_medians, freq, 'DateTime', 'ALARM', 'max signal', list(range(num_chs)),
                                  list(range(num_chs)))
                    if circle_buffer.check_init():
                        save_data(path_to_save_medians, freq, datetime.datetime.now(), alarm, max(sigs_array), sigs_array,
                                  circle_buffer.get_medians())
                # print(circle_buffer.get_buffer())
                # print(circle_buffer.get_medians())
                # print(circle_buffer.get_alarms())
            if debug_flag:
                single_alarm = circle_buffer.check_single_alarm(median, cur_channel)
                print(cur_channel, single_alarm)
                if single_alarm:
                    data = pack_elems(elems_to_save, file_types_to_save, signal, abs_signal)
                    #print('SAVE CURRENT SIGNAL SROCHNO TI MENYA SLISHISH?!?!?!?')
                    try:
                        remote_save_data(conn, data, module_name, freq, shared_folder, path_to_save_alarms)
                    except Exception as e:
                        print(f"Ошибка: {e}")
                #else:
                    #print('VSE OKI DOKI SIGNAL SOKHRANYAT NE NUZHNO!!!')

            f = multi_channel.change_channel()
        except Exception as e:
            print(str(e))
            print(".", end='')
    return f
