#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 5.5
#  in conjunction with Tcl version 8.6
#    Oct 17, 2020 02:43:11 PM CEST  platform: Windows NT

import sys, time
from weapon_fire_loop_generator import WeaponFireLoopGenerator

from tkinter.filedialog import askopenfile, askopenfiles, askdirectory

try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True

def set_Tk_var():
    global maxVolumeSample
    maxVolumeSample = tk.StringVar()
    maxVolumeSample.set('-12')
    global avgVolumeSample
    avgVolumeSample = tk.StringVar()
    avgVolumeSample.set('-12')
    global checkSoloSample
    checkSoloSample = tk.IntVar()
    global spinboxTailFadein
    spinboxTailFadein = tk.StringVar()
    global spinboxTailOffset
    spinboxTailOffset = tk.StringVar()
    global spinboxRandCents
    spinboxRandCents = tk.StringVar()
    global spinboxLoopFadeoutStart
    spinboxLoopFadeoutStart = tk.StringVar()
    global spinboxLoopFadeoutLength
    spinboxLoopFadeoutLength = tk.StringVar()
    global labelCurrentSampleName
    labelCurrentSampleName = tk.StringVar()
    labelCurrentSampleName.set('Sample Name')
    global labelAppLog
    labelAppLog = tk.StringVar()
    labelAppLog.set('Ready')
    global volumeHeadroomSample
    volumeHeadroomSample = tk.StringVar()
    global spinboxFireCount
    spinboxFireCount = tk.StringVar()
    global checkNormalize
    checkNormalize = tk.IntVar()
    global spinboxSeed
    spinboxSeed = tk.StringVar()
    global labelTargetDirectory
    labelTargetDirectory = tk.StringVar()
    labelTargetDirectory.set('Please Set Target Path')
    global spinboxRPM
    spinboxRPM = tk.StringVar()
    global spinboxRPMBurst
    spinboxRPMBurst = tk.StringVar()
    global spinboxBurstCount
    spinboxBurstCount = tk.StringVar()
    global textPrefix
    textPrefix = tk.StringVar()
    global checkMonoLoop
    checkMonoLoop = tk.IntVar()
    global checkMonoTail
    checkMonoTail = tk.IntVar()
    global spinboxVariations
    spinboxVariations = tk.StringVar()
    global maxVolumePreview
    maxVolumePreview = tk.StringVar()
    maxVolumePreview.set('-12')
    global avgVolumePreview
    avgVolumePreview = tk.StringVar()
    avgVolumePreview.set('-12')

def update_log(text):
    labelAppLog.set(text)
    w.LabelAppLog.update()

def init(top, gui, *args, **kwargs):
    global w, top_level, root, instance
    w = gui
    top_level = top
    root = top
    instance = WeaponFireLoopGenerator.create(update_log)
    update_loop_settings_view()

def changePathOfCurrentSampleButton(p1):
    directory = askdirectory()
    if directory:
        instance.change_path_current_sample(directory)
        update_sample_list_ui()

def exportProjectButton(p1):
    instance.export_project()

def generateGameFilesButton(p1):
    instance.export_all()

def importProjectButton(p1):
    config = askopenfile(mode ='r', filetypes =[('Config', '*.json')])
    if config:
        instance.import_project(config.name)
        update_loop_settings_view()
        update_sample_list_ui()
        
def onSelect(p1):
    selection = w.SourceFilesList.curselection()
    if selection:
        current_selection = w.SourceFilesList.get(selection[0])
        identifier = current_selection[-54:]
        samples = instance.sample_manager.get_samples_list()
        filtered = list(filter(lambda x: x.path.find(identifier) > -1, samples))
        instance.set_current_sample(filtered[0])
        update_sample_props_view()

def update_sample_props_view():
    if instance.current_sample:
        sample = instance.current_sample
        labelCurrentSampleName.set(sample.name)
        volumeHeadroomSample.set(sample.headroom)
        spinboxRandCents.set(sample.rand_offset_cents)
        spinboxLoopFadeoutStart.set(sample.loop_fadeout_start_ms)
        spinboxLoopFadeoutLength.set(sample.loop_fadeout_length_ms)
        spinboxTailOffset.set(sample.tail_offset_ms)
        spinboxTailFadein.set(sample.tail_fadein_ms)
        checkSoloSample.set(int(sample.solo))
        update_sample_volumes()

def update_sample_volumes():
    mono = instance.current_loop_settings.mono_loop or instance.current_loop_settings.mono_tail
    volumes = instance.current_sample.get_volumes(mono)
    maxVolumeSample.set(volumes[0])
    avgVolumeSample.set(volumes[1])

def on_sample_props_changed(p1):
   update_sample()

def update_sample():
    if instance.current_sample:
        try:
            instance.current_sample.set_headroom(float(volumeHeadroomSample.get()))
        except:
            pass

        if spinboxRandCents.get().isnumeric():    
            instance.current_sample.rand_offset_cents = int(spinboxRandCents.get())
        if spinboxLoopFadeoutStart.get().isnumeric():  
            instance.current_sample.loop_fadeout_start_ms = int(spinboxLoopFadeoutStart.get())
        if spinboxLoopFadeoutLength.get().isnumeric():    
            instance.current_sample.loop_fadeout_length_ms = int(spinboxLoopFadeoutLength.get())
        if spinboxTailOffset.get().isnumeric():
            instance.current_sample.tail_offset_ms = int(spinboxTailOffset.get())
        if spinboxTailFadein.get().isnumeric():
            instance.current_sample.tail_fadein_ms = int(spinboxTailFadein.get())

        instance.current_sample.solo = bool(checkSoloSample.get())
        update_sample_volumes()

        reset_select_sample(instance.current_sample)

def update_loop_settings_view():
    settings = instance.current_loop_settings

    spinboxFireCount.set(settings.fire_count)
    spinboxBurstCount.set(settings.burst_count)
    spinboxRPM.set(settings.rpm)
    spinboxRPMBurst.set(settings.rpm_burst)
    spinboxSeed.set(settings.seed)
    spinboxVariations.set(settings.variations)

    textPrefix.set(settings.prefix)
    checkNormalize.set(int(settings.normalize))
    checkMonoLoop.set(int(settings.mono_loop))
    checkMonoTail.set(int(settings.mono_tail))
    
    directory = instance.current_loop_settings.target_path
    labelTargetDirectory.set(WeaponFireLoopGenerator.prevent_overflow(directory, 54)) # prevent overflow 

def update_loop_settings():
    if spinboxFireCount.get().isnumeric():  
        instance.current_loop_settings.fire_count = int(spinboxFireCount.get())
    if spinboxBurstCount.get().isnumeric():  
        instance.current_loop_settings.burst_count = int(spinboxBurstCount.get())
    if spinboxRPM.get().isnumeric():  
        instance.current_loop_settings.rpm = int(spinboxRPM.get())    
    if spinboxRPMBurst.get().isnumeric():  
        instance.current_loop_settings.rpm_burst = int(spinboxRPMBurst.get())    
    if spinboxSeed.get().isnumeric():  
        instance.current_loop_settings.seed = int(spinboxSeed.get())   
    if spinboxVariations.get().isnumeric():  
        instance.current_loop_settings.variations = int(spinboxVariations.get())   
    
    instance.current_loop_settings.prefix = textPrefix.get().strip()
    instance.current_loop_settings.normalize = bool(checkNormalize.get())
    instance.current_loop_settings.mono_loop = bool(checkMonoLoop.get())
    instance.current_loop_settings.mono_tail = bool(checkMonoTail.get())

    reset_select_sample(instance.current_sample)

def on_loop_settings_changed(p1):
    update_loop_settings()


def openFilesButton(p1):
    files = askopenfiles(mode ='r', filetypes =[('PCM', '*.wav')])
    if files:
        paths = list(map(lambda currFile: currFile.name, files))
        instance.open_files(paths)
        update_sample_list_ui()

def update_sample_list_ui():
    samples = instance.sample_manager.get_samples_list()
    i = 0
    w.SourceFilesList.delete(0, 99999999)
    for sample in samples:
        sample_path = WeaponFireLoopGenerator.prevent_overflow(sample.path, 66) # prevent overflow 
        w.SourceFilesList.insert(i, sample_path)
        i = i + 1
    if len(samples) > 0:
        reset_select_sample(instance.current_sample)
    update_sample_props_view()

def reset_select_sample(sample):
    w.SourceFilesList.select_clear(0, "end")
        
    if sample:
        samples = instance.sample_manager.get_samples_list()
        index = samples.index(sample)
        w.SourceFilesList.selection_set(index)
        w.SourceFilesList.see(index)
        w.SourceFilesList.activate(index)
        w.SourceFilesList.selection_anchor(index)

def playLoopSampleButton(p1):
   instance.play_current_loop_sample()

def playPreviewButton(p1):
    instance.play_preview()

def playTailSampleButton(p1):
    instance.play_current_tail_sample()

def regeneratePreviewBurstButton(p1):
    instance.render_preview_burst()
    if instance.current_preview:
        maxVolumePreview.set(round(instance.current_preview.max_dBFS, 2))
        avgVolumePreview.set(round(instance.current_preview.dBFS, 2))

def regeneratePreviewLoopButton(p1):
    instance.render_preview_loop()
    if instance.current_preview:
        maxVolumePreview.set(round(instance.current_preview.max_dBFS, 2))
        avgVolumePreview.set(round(instance.current_preview.dBFS, 2))

def reloadAllSamplesButton(p1):
    instance.reload_samples()
    update_sample_list_ui()

def removeCurrentSampleButton(p1):   
    instance.remove_current_sample()
    update_sample_list_ui()

def setTargetDirectoryButton(p1):
    directory = askdirectory()
    if directory:
        instance.set_target_directory(directory)
        update_loop_settings_view()

def buttonCopy(p1):
    instance.copy_current_sample_props()

def buttonPaste(p1):
    instance.paste_current_sample_props()
    update_sample_props_view()

def destroy_window():
    # Function which closes the window.
    global top_level
    top_level.destroy()
    top_level = None

if __name__ == '__main__':
    import weapon_fire_loop_generator_ui
    weapon_fire_loop_generator_ui.vp_start_gui()




