# coding=UTF-8
# -*- coding: UTF-8 -*-
# Open CD/DVD disktree html rendering utilities for windows OS 

import codecs
import string, re
import os
import mylibs

import configs as config

linkify_kmeleon = re.compile(r'("http://[^"]+")|(\'http://[^\']+\')')
re_file = re.compile(config.file_mask)

installable_files = []
installable_files_used = []
new_lch_list = []

exclude_dirs = 'Gimp/Portatyvus/App'.split(';')
def has_fragment2exclude(dir):
    res = False
    ##dir = dir.replace('\\', '/')
    for fragment in exclude_dirs:
        if dir.find(fragment) > -1:
            res = True
    return res

def callback_scan(arg, directory, files):
    for file in files:
        if re_file.match(file) and not has_fragment2exclude(directory):
            full_path = os.path.join(directory, file)
            installable_files.append(full_path.replace('\\', '/'))
os.path.walk(config.win_installs_rel2generator, callback_scan, config.file_mask)





lch_tpl = '''[Launch]
ExecuteFile=${cwd}$pathtofile''';

url_lch_tpl = '''
[Launch]
ExecuteFile=$url
''' ##ExecuteParameter=${cwd}$parameter


 # ******** WIN specific functions *********

def look_for_install_file(fname_fragment):
    fname_fragment = fname_fragment.lower()
    for file_path in installable_files:
       fname = file_path.split('/')[-1]
       #if re.compile(fcodename).search(fname):
       if fname.lower().find(fname_fragment) != -1:
           installable_files_used.append(file_path)
           return file_path
    return ''
#def look4_wininstall(fname_fragment): return look_for_install_file(fname_fragment); ##

def linkify_4kmeleon(url):
    if targetbrowser == 'kmeleon':
        url2fname = clean_url4fname(url)
    ## !!! LAbai svarbu nekurti labai ilgu vardu - max 63 simboliai, nes paskui CD/DVD gali Windai neskaityt
        ##htmlfname = 'external/'+url2fname+'.redirect.html'
        lchfname = lch_path+'external/'+ url2fname + '.lch'
        ##putftext(htmlfname, url_redirect_tpl.replace('$url', url))
        url_lch_txt = url_lch_tpl.replace('$url', url)  ##lch_start_node_html+htmlfname
        putftext(lchfname, url_lch_txt)
        rezurl = lchfname
    ##elif targetbrowser == 'welcomecenter':
     ##   rezurl = url
    else: rezurl = url
    return rezurl
    
    
def filter_linkify_4kmeleon(src):
    rez = src
    if targetbrowser == 'kmeleon':
        ##rez = linkify_kmeleon.sub( '"external/' + clean_url4fname('\\1') + '.lch"', src)
        for match in re.finditer(linkify_kmeleon, src):
            url = match.group(0).strip('\'"')
            lchfname = linkify_4kmeleon(url)
            rez = rez.replace(url, lchfname)
    return rez

    
def prepair_lch_path(_progname, wininstallname=''):
    if wininstallname.strip() == '': wininstallname = _progname
    install_path = look_for_install_file(wininstallname) 
    file_lch = config.lch_root_rel2generator+_progname+'.lch'
    diropen_lch = config.lch_root_rel2generator+_progname+'.diropen.lch'
    if install_path:
        ##__ print  install_path, ' | ', _progname, '--', wininstallname
        install_dir = '/'.join(install_path.split('/')[:-1])
##        if mylibs.file_exists(lch_fname) == False: # TODO: think: don't overwrite if exists (may be should force overwrite??)
        ##__ print 'CREATE ', file_lch
        pathtofile_rel2launchexe =  config.win_installs_rel2launchexe + install_path[len(config.win_installs_rel2generator):] #ajust file path for lch
        pathtodir_rel2launchexe =  config.win_installs_rel2launchexe + install_dir[len(config.win_installs_rel2generator):]
        new_lch_list.append(file_lch)
        mylibs.putftext(file_lch, lch_tpl.replace('$pathtofile', pathtofile_rel2launchexe.replace('/', '\\'))) #TODO: attention: check if OK
        mylibs.putftext(diropen_lch, lch_tpl.replace('$pathtofile', pathtodir_rel2launchexe.replace('/', '\\'))) #TODO: attention: check if OK        
        install_file_found = True;
    else:
        print 'NO INSTALL FOUND: ', _progname
        install_file_found = False;
        install_dir = ''
    ##if internet_stuff: install_file_found = False;

    install_type = '' #none
    if install_file_found:              #discover install method (installation file type)
        flch = open ( file_lch, 'r' )
        lch_txt = flch.read()
        if lch_txt.find('.direct')  > -1:
            install_type = 'rundirectly'
        elif (lch_txt.find('.exe') > -1) or (lch_txt.find('.com') > -1) or (lch_txt.find('.msi') > -1 ) :
            install_type = 'exe'
        elif lch_txt.find('.zip') > -1:  ##re.compile(r'.*\.(zip|7z|tgz|gz|tar|rar)').match(lch_txt):  ##
            install_type = 'zip'
        elif lch_txt.find('.jar') > -1:  ##re.compile(r'.*\.(zip|7z|tgz|gz|tar|rar)').match(lch_txt):  ##
            install_type = 'jar'
        flch.close()
    
    return (install_type, install_path, install_dir, file_lch, diropen_lch)  ## actually install_type could be enough

##        if install_type == 'rundirectly' :
##            _install = unicode('<a href="../lch/'+ _progname +u'.lch" title=\'Tiesiogiai paleisti "'+progname+u'"\' > \
##            <img src="../images/rundirectly.png"  alt=\'Tiesiogiai paleisti "'+progname+'"\' align="right" border="0"></a>')
##        elif install_type == 'exe' :
##            _install = '<a href="../lch/'+ _progname +u'.lch" title=\'Įdiegti "'+progname+'"\' > \
##            <img src="../images/install_smaller.png"  alt=\''+u'Įdiegti "'+progname+'"\' align="right" border="0"></a>'
##        elif install_type == 'zip' :
##            _install = unicode('<a href="../lch/'+ _progname +u'.lch" title=\'Išpakuoti "'+progname+u'"\' > \
##            <img src="../images/install_zip.png"  alt=\'Išpakuoti "'+progname+'"\' align="right" border="0"></a>')
##        elif install_type == 'jar' :
##            _install = unicode('<a href="../lch/'+ _progname +u'.lch" title=\'Instaliuoti (java start) "'+progname+u'"\' > \
##            <img src="../images/install_jar.gif"  alt=\'Instaliuoti (java start) "'+progname+'"\' align="right" border="0"></a>')
        #elif  install_file_found == False: _install = ''
        #end if targetos == 'w'    
##        return _install

