#/usr/bin/python

from remi.gui import *
from cvs import *


class untitled(App):
    def __init__(self, *args, **kwargs):
        #DON'T MAKE CHANGES HERE, THIS METHOD GETS OVERWRITTEN WHEN SAVING IN THE EDITOR
        if not 'editing_mode' in kwargs.keys():
            super(untitled, self).__init__(*args, static_file_path={'my_res':'./res/'})

    def idle(self):
        #idle function called every update cycle
        if self.info:
            with open(self.filepath+"/.pybd.log", "r") as f: 
                data = f.read()
                self.lbl.set_text(data)
                print(data)
                f.close()
        # else:
        #     self.lbl.set_text("...")


        pass
    
    def main(self):
        return untitled.construct_ui(self)
        
    @staticmethod
    def construct_ui(self):
        #DON'T MAKE CHANGES HERE, THIS METHOD GETS OVERWRITTEN WHEN SAVING IN THE EDITOR
        vbox0 = VBox()
        vbox0.attr_editor_newclass = False
        vbox0.css_align_items = "center"
        vbox0.css_background_color = "rgb(198,193,197)"
        vbox0.css_display = "flex"
        vbox0.css_flex_direction = "column"
        vbox0.css_height = "96%"
        vbox0.css_justify_content = "space-around"
        vbox0.css_left = "10px"
        vbox0.css_margin = "0px"
        vbox0.css_position = "absolute"
        vbox0.css_top = "20px"
        vbox0.css_width = "100%"
        vbox0.variable_name = "vbox0"
        self.btFileDiag = Button('Choose Your .Py File', width=300, height=30, margin='10px')
        self.btFileDiag.css_width = "95%"
        self.btFileDiag.onclick.do(self.open_fileselection_dialog)

        self.btDataDiag = Button('Choose Other Files Used By Py（Optional） ', width=300, height=30, margin='10px')
        self.btDataDiag.css_width = "95%"
        self.btDataDiag.onclick.do(self.open_DataModel_dialog)
        #self.btDataDiag.css_width = "95%"
        #self.btFileDiag..css_width = "95%"
        
        vbox0.append(self.btFileDiag,'btFileDiag')
        vbox0.append(self.btDataDiag,'btDataDiag')
        button0 = Button()
        button0.attr_editor_newclass = False
        button0.css_height = "30px"
        button0.css_margin = "0px"
        button0.css_order = "521528744480"
        button0.css_position = "static"
        button0.css_top = "20px"
        button0.css_width = "95%"
        button0.text = "Build Apk Now!"
        button0.variable_name = "button0"
        vbox0.append(button0,'button0')
        button0.onclick.do(self.on_button0_click)
        textinput0 = TextInput()
        textinput0.attr_editor_newclass = False
        textinput0.css_height = "78%"
        textinput0.css_margin = "0px"
        textinput0.css_order = "521151828432"
        textinput0.css_position = "static"
        textinput0.css_top = "20px"
        textinput0.css_width = "95%"
        textinput0.text = ""
        textinput0.variable_name = "textinput0"
        vbox0.append(textinput0,'textinput0')
        self.lbl=textinput0

        self.vbox0 = vbox0
        self.filename=''
        self.filepath=''
        self.datapath=''
        self.info=False
        return self.vbox0
    
    def on_fileselection_dialog_confirm(self, widget, filelist):
        # a list() of filenames and folders is returned
        self.lbl.set_text('Selected Py File: %s' % ','.join(filelist))
        if len(filelist):
            self.filename = filelist[0]
            self.datapath = ''
            self.lbl.set_text('Selected Py File: %s' % ','.join(filelist))
        #     # replace the last download link
        #     fdownloader = gui.FileDownloader("py selected", f, width=200, height=30)
        #     self.subContainerRight.append(fdownloader, key='file_downloader')
    
    def on_data_dialog_confirm(self, widget, filelist):
        # a list() of filenames and folders is returned
        self.lbl.set_text('Selected data or model : %s' % ','.join(filelist))
        if len(filelist):
            self.datapath = filelist[0]

    def open_fileselection_dialog(self, widget):
        self.fileselectionDialog = FileSelectionDialog('File Selection Dialog', 'Select files and folders', False,
                                                           '/home')
        self.fileselectionDialog.confirm_value.do(
            self.on_fileselection_dialog_confirm)
        # here is returned the Input Dialog widget, and it will be shown
        self.fileselectionDialog.show(self)

    def open_DataModel_dialog(self, widget):
        self.dataelectionDialog = FileSelectionDialog('Data Selection Dialog', 'Select files and folders', False,
                                                           '/home')
        self.dataelectionDialog.confirm_value.do(
            self.on_data_dialog_confirm)
        # here is returned the Input Dialog widget, and it will be shown
        self.dataelectionDialog.show(self)
    
    def on_button0_click(self, widget):
        if self.filename=='':
             self.lbl.set_text('pls choose py file to be build...')
        else : 
            self.lbl.set_text('Start build now ... ')
            self.t = threading.Thread(target=self.build_now)
            self.t.start()
            
    def build_now(self):
        (filepath, filename) = os.path.split(self.filename)
        self.filepath=filepath
        self.info=True
        x=commands.getstatusoutput("cd "+filepath+"; rm .pybd.log; echo 'import apkneed'>>"+filename+";pyinstaller -F "+filename+" >.pybd.log 2>&1" )
        self.info=False
        self.lbl.set_text("wait ...")
        self.info=True
        self.filepath="/home"
        
        x=commands.getstatusoutput("cd "+filepath+";cp -r dist /home/;cd /home;cp -r "+self.datapath+" /home/dist/;rm .e.sh;echo 'cd /root/dist;./"+filename[:-3]+"' >>.e.sh;./apkbuild dist >.pybd.log 2>&1")
        
#processing_code

# def process():

#     cap=cvs.VideoCapture(1)
    
#     while True:
#         sleep(30)
#         img =cap.read()

#         if img is None :
#             continue
#         cvs.imshow(img)

if __name__ == "__main__":
#    initcv(cvs.openwin)
#    startcv(untitled)
    start(untitled, debug=False, address='0.0.0.0', port=8084,update_interval=0.05, multiple_instance=True,start_browser=False)

