# Ce programme python contient dans le meme repertoire :
#     texte a convertir.txt : le code mediawiki a traduire
#     texte converti.txt    : le bbcode cms obtenu après exécution du script

B=[]

#tableaux
B =B +  ['[table style=" ','"]','<table','>']
B =B +  ['[row]','','<tr>','']
B =B +  ['[/row]','','</tr>','']
B =B +  ['[col]','','<td>','']
B =B +  ['[col style=" ','"]','<td ','>']
B =B +  ['[/col]','','</td>','']
B =B +  ['width: ',';','width="','"']
B =B +  ['border-spacing: ','; ','border="','"']
B =B +  ['margin: ','; ','cellspacing="','"']
B =B +  ['padding: ','; ','cellpadding="','"']

B =B +  ['','', '<div align="center">', '']# alignement déjà au centre par defaut
B =B +  ['','', '<div align="right">', '']# non-géré ! 
B =B +  ['','', '<div align="left">', '']# non-géré !
B =B +  ['','','</div>','']# inutile

B =B +  ['[/table]','','</table>','']

# termes non-geres, a eliminer

B =B +  ['', '', '<br/>', ''] # ? saut de ligne ?
B =B +  ['', '', '[[Catégorie:', ']]'] # + supprimer le texte associe

B =B +  ['', '', '<Gallery>', '']
B =B +  ['', '', '</Gallery>', '']

B =B +  ['', '', '|frameless', '']
B =B +  ['', '', '|thumb', ''] 
B =B +  ['', '', '|left', '']
B =B +  ['', '', '|none', '']

B =B +  ['', '', '{|', '']
B =B +  ['', '', '|}', '']

B =B +  ['', '', '|450px', ''] # Réglage img à dégager
B =B +  ['', '', '|300px', ''] # Réglage img à dégager
B =B +  ['', '', '|200px', ''] # Réglage img à dégager
B =B +  ['', '', '|150px', ''] # Réglage img à dégager

# plan du texte
B =B +  [' ----- ', '', '=====', ''] # Toujours la plus longue chaine en 1er
B =B +  [' ---- ', '', '====', ''] #   pour éviter la recursivite
B =B +  [' --- ', '', '===', '']
B =B +  [' -- ', '', '==', '']
B =B +  ['-- ', '', '--  ', ''] # mise en forme des
B =B +  [' --', '', '  --', ''] # chapitres(un seul espace avant/après)

#divers
B =B +  ['[code]', '[/code]', '<nowiki>', '</nowiki>']
B =B +  ['[youtube=560,315]https://www.youtube.com/watch?v=', '[/youtube]', '[https://www.youtube.com/watch?v=', ' Voir la vidéo]']
B =B +  ['[dm]', '[/dm]', '[https://www.dailymotion.com/video/', ' Voir la vidéo]']
B =B +  ['[vimeo]', '[/vimeo]', '[https://vimeo.com/', ' Voir la vidéo]']
B =B +  ['[size=', ']', '<p style="font-size:', ';">']
B =B +  ['[/size]', '', '</p>', '']
B =B +  ['[quote]', '', '<blockquote>', '']
B =B +  ['[/quote]', '', '</blockquote>', '']

#styles gras, italique souligne
B =B +  ['[b]', '','<b>','']
B =B +  ['[i]', '','<i>','']
B =B +  ['[u]', '','<u>','']
B =B +  ['[/b]', '','</b>','']
B =B +  ['[/i]', '','</i>','']
B =B +  ['[/u]', '','</u>','']
B =B +  ['[b]', '[/b]', "'''", "'''"]
B =B +  ['[i]', '[/i]', "''", "''"]
B =B +  ['[u]', '[/u]', '<u>', '</u>']

#couleurs
B =B +  ['[color=#', ']', '<span style="color:#', ';">']
B =B +  ['[/color]', '', '</span>', '']

#smileys
B =B +  [':D', '', '[[image:icon_biggrin.gif]]', '']
B =B +  [':)', '', '[[image:icon_smile.gif]]', '']
B =B +  [':(', '', '[[image:icon_sad.gif]]', '']
B =B +  [':shock:', '','[[image:icon_eek.gif]]', '']
B =B +  ['8)', '', '[[image:icon_cool.gif]]', '']
B =B +  [':lol:', '', '[[image:icon_lol.gif]]', '']
B =B +  [':mad:', '', '[[image:icon_mad.gif]]', '']
B =B +  [':P', '', '[[image:icon_razz.gif]]', '']
B =B +  [':oops:', '', '[[image:icon_redface.gif]]', '']
B =B +  [':o', '', '[[image:icon_surprised.gif]]', '']
B =B +  [':cry', '', '[[image:icon_cry.gif]]', '']
B =B +  [':evil:', '', '[[image:icon_evil.gif]]', '']
B =B +  [':twisted:', '', '[[image:icon_twisted.gif]]', '']
B =B +  [':roll:', '', '[[image:icon_rolleyes.gif]]', '']
B =B +  [':wink:', '', '[[image:icon_wink.gif]]', '']
B =B +  [':!:', '', '[[image:icon_exclaim.gif]]', '']
B =B +  [' :???: ', '', '[[image:icon_confused2.gif]]', '']
B =B +  [':?:', '', '[[image:icon_question.gif]]', '']
B =B +  [':?', '', '[[image:icon_confused.gif]]', '']
B =B +  [':idea:', '', '[[image:icon_idea.gif]]', '']
B =B +  [':arrow:', '', '[[image:icon_arrow.gif]]', '']
B =B +  [':|', '', '[[image:icon_neutral.gif]]', '']
B =B +  [':mrgreen:', '', '[[image:icon_mrgreen.gif]]', '']
B =B +  [':hang:', '', '[[image:icon_hangloose.gif]]', '']
B =B +  [':/: ', '', '[[image:icon_unhappy.gif]]', '']
B =B +  [' :zyeuxkipic: ', '', '[[image:icon_exorbite.gif]]', '']
B =B +  [' :help ', '', '[[image:icon_helpme.gif]]', '']
B =B +  [' :love ', '', '[[image:icon_love.gif]]', '']
B =B +  [' :mdr-f ', '', '[[image:icon_mdr-f.gif]]', '']
B =B +  [' :bravo ', '', '[[image:icon_bravo.gif]]', '']
B =B +  [' :tongue ', '', '[[image:icon_tongue.gif]]', '']
B =B +  [' :jmincline ', '', '[[image:icon_remarquable.gif]]', '']
B =B +  [' :gna: ', '', '[[image:icon_neztourne-f.gif]]', '']
B =B +  [' :excitee: ', '', '[[image:icon_excitee.gif]]', '']
B =B +  [' :ptdr ', '', '[[image:icon_ptdr.gif]]', '']
B =B +  [' :pong ', '', '[[image:icon_pong.gif]]', '']
B =B +  [' :meaculpa ', '', '[[image:icon_mea-culpa.gif]]', '']
B =B +  [' :top: ', '', '[[image:icon_top.gif]]', '']
B =B +  [' :dcroises ', '', '[[image:icon_jcroiselesdoigts.gif]]', '']
B =B +  [' :respect ', '', '[[image:icon_respect.gif]]', '']
B =B +  [' :hangf: ', '', '[[image:icon_hangloose-f.gif]]', '']
B =B +  [' :sante ', '', '[[image:Icon_ahoy.gif]]', '']
B =B +  [' :tchin ', '', '[[image:Icon_tchin.gif]]', '']
B =B +  [' :ahyo ', '', '[[image:Icon_ahoy2.gif]]', '']
B =B +  [' :joke ', '', '[[image:icon_joke.gif]]', '']
B =B +  [' :cartonjaune: ', '', '[[image:Icon_foot-carton-jaune.gif]]', '']
B =B +  [' :cartonrouge ', '', '[[image:Icon_foot-carton-rouge.gif]]', '']
B =B +  [' :nrv ', '', '[[image:icon_nrv.gif]]', '']
B =B +  [' :furax ', '', '[[image:icon_furax.gif]]', '']
B =B +  [' :idea ', '', '[[image:icon_idea2.gif]]', '']
B =B +  [' :wtf ', '', '[[image:icon_wtf.gif]]', '']
B =B +  [' :think ', '', '[[image:icon_think.gif]]', '']
B =B +  [' :cramer ', '', '[[image:Icon_Cramer.gif]]', '']
B =B +  [' :CramerJ ', '', '[[image:Icon_CramerJ.gif]]', '']
B =B +  [' :merci ', '', '[[image:Icon_pancarte-merci.gif]]', '']
B =B +  [' :+1: ', '', '[[image:Icon_pancarte-plus1.gif]]', '']
B =B +  [' :poups ', '', '[[image:Icon_pancarte-oops.png]]', '']
B =B +  [' :tusort ', '', '[[image:Icon_pancarte-tusort.gif]]', '']
B =B +  [' :tgenial ', '', '[[image:icon_tgenial.gif]]', '']
B =B +  [' :upup ', '', '[[image:Icon_pancarte-upup.gif]]', '']
B =B +  [' :gne? ', '', '[[image:Icon_pancarte-gne.gif]]', '']
B =B +  [' :bienvwenue: ', '', '[[image:Icon_bienvwenue.gif]]', '']
B =B +  [' :vatependre ', '', '[[image:Icon_pancarte-va-te-pendre.gif]]', '']
B =B +  [' :fuck ', '', '[[image:Icon_pancarte-fuck.gif]]', '']
B =B +  [' :dejadehors ', '', '[[image:Icon_pancarte-deja-dehors.gif]]', '']
B =B +  [' :heh-hee:', '', '[[image:icon_heh-hee.gif]]', '']

#images
B =B +  ['[img]/upload/mw_images/', '[/img]', '[[image:', ']]']         # balise image "classique"
B =B +  ['[img]/upload/mw_images/', '[/img]', 'image:', '|']  # le cas particulier gallery : pas de [[ mais separateurlien externe

#lien externe
B =B +  ['[url]http://', '[/url]', '[http://', ']'] 

#lien interne
B =B +  ['[link]', '[/link]', '[[', ']]']

# conversion des caracteres speciaux
H=[]

H=H+[' ','_'] #supprimer espaces
H=H+[':','_']

H=H+['à','a']
H=H+['â','a']
H=H+['ä','a']

H=H+['ç','c']

H=H+['é','e']
H=H+['è','e']
H=H+['ê','e']
H=H+['ë','e']

H=H+['ï','i']
H=H+['î','i']

H=H+['ô','o']
H=H+['ö','o']

H=H+['ù','u']
H=H+['û','u']
H=H+['ü','u']


H=H+['__','_'] # suppression des 
H=H+['__','_'] # espaces multiples


#try: (pas utilise pour debug)
if 1==1:
    # la conversion peut commencer !
    destination = open('texte converti.txt', "w")
 
    with open('texte a convertir.txt','r')as source:
        nblignevide=0
        for ligne in source:
            A=(ligne.strip('\n'))            
            if A=='':
                nblignevide= nblignevide +1
            else:
                nblignevide =0
 
            # recherche mots clé    
            for i in range(0,len(B),4):
                for j in range(0,10):
                    C=A.lower().find(B[i+2].lower()) # 1er mot cle (insensible a la casse)
                    if C<0:    # introuvable dans cette ligne :
                        break  # abandon
 
                    if len(B[i+3])>0:
                        D=A.lower().find(B[i+3].lower(),C+len(B[i+2]))    # 2e mot cle présent ?
                    else:
                        D=-1
                    if D<0:  #un seul remplacement ?
                        A=A[:C]+B[i]+A[C+len(B[i+2]):]                        
                    else: # 2 remplacements                                             
                        A=A[:C]+B[i]+A[C+len(B[i+2]):D]+B[i+1]+A[D+len(B[i+3]):]
                        C=C+len(B[i])
                        D=D+len(B[i])-len(B[i+2]) # Mots clé remplacés. Ils contiennent une chaîne entre C et D
                    
                    
                    # Cas particuliers
                        if B[i+2]=='[[Catégorie:': 
                            A=A[:C]+ A[D:] #supprimer les catégories
                                                
                        if B[i+1]=='[/url]' or B[i+1]=='[/link]' or B[i+1]=='[/img]': #recherche lien (separateur + texte)
                            if B[i+1]=='[/url]':
                                S=' ' # separateur lien externe
                            else:
                                S='|' # separateur lien interne
                                               
                            E=A.find(S,C) # rechercher le separateur lien/texte
                            
                            if E<0 and B[i+1]=='[/link]': # pas de texte associe au lien interne ? il-apparaittrait-comme-ca-pas-beau
                                G='|'+A[C:D] # on duplique le texte du lien 
                                F=G.replace('_',' ') # supprimer les _ du texte pour la lisibilite
                                A=A[:D]+F+A[D:]
                                
                                print(A)
                                E=D # actualiser position du |separateur 
                                D=D+len(F) # actualiser longueur de chaîne
                                
                            if E>0 and E<(D): # si le texte alternatif existe
                                A=A[:C-1]+'='+A[C:]# remplacer [ par =
                                A=A[:E]+']'+A[E+1:]# remplacer espace par ]
                                D=E                                
                                
                            # formater le lien interne : en minuscules, ni espace ni accents
                            if S=='|':
                                G=A[C:D]
                                F=G.strip(" ") # supprimer espaces parasites eventuels
                                
                                for k in range(0,len(H),2):
                                    G=F.replace(H[k],H[k+1]) # liste des modifs voir la table 'H = H + ...'  plus haut
                                    F=G
                                    
                                if B[i+1]=='[/link]': #liens internes:
                                    G=F.lower()          # en minuscules
                                    F=G.replace('_','-') # tiret remplace underscore 

                                A=A[:C] + F + A[D:]

            if nblignevide< 2:
                destination.write(A+"\n")
                #print (A)
    destination.close()
    print('Conversion terminée !')
    print('Le résultat de la conversion se trouve dans le fichier suivant :')
    print('"texte converti.txt"')
    print
 
#except:
if 1==0:    
    if 1==0:    
        print('Le fichier à traiter:')
        print('"texte a convertir.txt"')
        print('est introuvable. Il doit être dans le même répertoire que ce programme !')
        print
    else:
        print(Exception)
    
 
 
