#!/usr/bin/python3.11

import sys, os
os.system('uname -a')
os.system('id')
os.system('cat /etc/os-release')

from datetime import datetime
app_start_time = datetime.now().strftime("%y-%m-%d_%H:%M:%S_%f")
print('App start time: ', app_start_time)

import glob

# print("trying to import backend")
# print('finish importing backend')

print("trying to import gradio")
import gradio as gr
print('finish importing gradio')

############################################################

os.system('tar -xvf vsf-linux-dyn.tar.gz  -C  vsf-linux-dyn')

def greet(video, enable_area, ymin, ymax, xmin, xmax):
    # os.system('./videosubfinder-cli-cpu-static-linux-x64/VideoSubFinderCli.run --help')
    
    os.system('ldd ./vsf-linux-dyn/VideoSubFinderCli')
    os.system('./vsf-linux-dyn/VideoSubFinderCli.run --help')
    
    print('输入的文件为', video)
    
    debug_output = ""
    srt_file_content = ""
    srt_file_path = None 
    
    if not video:
        debug_output += "ERROR: input video is not true \n" 
        srt_file_content = "ERROR: input video is not true"
        
    if enable_area:
        subtitle_area = (ymin, ymax, xmin, xmax)
    else:
        subtitle_area = None
        
    if video:
        print("检测到输入video对象,准备开始处理")
        print('开始于 ', datetime.now().strftime("%y-%m-%d_%H:%M:%S_%f") )
        debug_output += '开始于 ' + datetime.now().strftime("%y-%m-%d_%H:%M:%S_%f") + '\n'
        ( srt_file_content , srt_file_path , sub_debug_output) = main.main(video, subtitle_area )
        print('完成于 ', datetime.now().strftime("%y-%m-%d_%H:%M:%S_%f") )
        debug_output += '完成于 ' + datetime.now().strftime("%y-%m-%d_%H:%M:%S_%f") + '\n'
        debug_output += sub_debug_output + '\n'
        
        print('---------运行输出结果------\n\n')
        print(srt_file_content)
        print('\n-------------------------\n')
        
        if not srt_file_path or (srt_file_path and not os.path.isfile(srt_file_path) ) :
            debug_output += 'ERROR: srt file path ' + srt_file_path + ' file not valid \n'
            srt_file_path = None
            
        
    return \
        srt_file_content , \
        srt_file_path, \
        debug_output, \
            
############################################################

allFilesGlob = '/tmp/gradio/*/**'
def getAllFiles():
    all_possible_files = []
    for x in glob.glob(allFilesGlob, recursive=True):
        if os.path.isfile(x):
            print('找到个可能文件',x)
            all_possible_files.append(x)
    
    print(all_possible_files)
    return all_possible_files

def delAllFiles():
    for x in glob.glob(allFilesGlob, recursive=True):
        if os.path.isfile(x):
            print('deleting file', x)
            os.remove(x)
    return "Finished deleting all files in " + allFilesGlob

####################################################################            

print('setting gradio interface')
    

with gr.Blocks() as app:
    gr.Markdown("just test")
    with gr.Tab("ttest"):
        with gr.Row():
            with gr.Column():
                inputs = [
                    gr.Video(label='input video with enbedded subtitle'), 
                    gr.Checkbox(label='enable area'), 
                    gr.Slider(0, 10000, value=800, step=1, label="y min"), 
                    gr.Slider(0, 10000, value=1079, step=1, label="y max"), 
                    gr.Slider(0, 20000, value=1, step=1, label="x min"), 
                    gr.Slider(0, 20000, value=1910, step=1, label="x max"), 
                ]
                btn_ttest = gr.Button("Run ttest")
            with gr.Column():
                outputs = [
                    gr.Textbox(label="subtitle srt content"), 
                    gr.File(label="output subtitle srt file"), 
                    gr.Textbox(label="debug output"), 
                ]
    with gr.Tab("get files"):
        btn_allfiles = gr.Button("Get all files")
        outputs2 = [gr.File(label='all possible files')]
    with gr.Tab('del files'):
        btn_delfiles = gr.Button("Delete all gradio tmp files")
        outputs3 = [gr.Textbox()]
    
    btn_ttest.click(greet, inputs=inputs, outputs=outputs)
    btn_allfiles.click(getAllFiles, inputs=[], outputs=outputs2)
    btn_delfiles.click(delAllFiles, inputs=[], outputs=outputs3)
    
    
# app = gr.Interface(fn=greet, inputs=inputs, outputs=outputs)
    
print('launching gradio app')
app.queue(max_size=30, api_open=True)
app.launch( show_error=True, server_name='0.0.0.0' )