# -*- coding: utf-8 -*-

# Change log
#
#   2020/5/5:
#      * 3 authors, and the name of the first one ends with \cH33
#
#   2019/1/8:
#      * slightly change the message of searching for bib.
#
#   2018/3/23:
#      * fixed bug: when calling cwtex.py, option is "-l" for latin-1, instead of "-e"
#
#   2018/2/28:
#      * check if there is at least one citation in the document
#
#   2018/2/7:
#      * Add -E ascii option to biber
#
#


"""
cwtex 5.1 system
(cwtex.py, tex2xtc.py, cwbiblatex.py, cwmkidx.py, cwmkgls.py, cwcjksort, cwhtml)

Copyright (C) 2018 Tsong-Min Wu and Tsong-Huey Wu
  with support of ...

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, see <http://www.gnu.org/licenses/>
"""

import shutil, os, sys, configparser, logging, time, unicodedata
import re

from cwfont_decode import *
from sys import argv
# script, backend, inputfile = argv            # backend = biber or bibtex
script, backend, engine, inputfile = argv      # engine = luatex or pdftex

# luatex = 1

# assume that there is at least one citation in the document
# if not citenum = 0

citenum = 1     
                

zhuyinon = 0
# Default: inputfile has file extension .ctx,

if inputfile.split(".")[0] == inputfile:  # No file extension
	inputfile = inputfile + ".ctx"
basename = inputfile.split(".")[0]

logging.basicConfig(format='%(lineno)d %(message)s')
inpinc = re.compile(r'\\(input|include){([-_a-zA-Z\d]+)}')       # Searching \\input{...}, \\include(...)

bcfname = basename + ".bcf"
auxname = basename + ".aux"

### do we need this? probably not, 2016.4.30
# file = open(inputfile, encoding='utf-8')

# In .bcf, search for     >tmwu-blx.bib<
sbib = re.compile(r'>([-_.a-zA-Z\d]+).bib<')

biblist=[]

# 20180228
# search for "bcf:citekey order" in .bcf, if not found, there is no citekey in current document
# so no need for further processing

if backend == "biber":
    bcffile = open(bcfname, 'r', encoding='latin-1')
#    bcffile = open(bcfname, 'r', encoding='utf-8')
    with open(bcfname) as myfile:                   
        if not "bcf:citekey order" in myfile.read():
             citenum = 0    
    if citenum == 1:                                 
        lines = bcffile.readlines()                                      
        for linei in range(len(lines)):                                  
            str1 = lines[linei]                                          
            i = 0                                                        
            linelength = len(str1)                                       
            while i != linelength:                                       
                b = re.findall(r'>([-_a-zA-Z\d]+)\.bib<', str1[i:])      
                if b:                                                    
                    b_str = ''.join(b[0]).strip(">").strip("<") + ".bib" 
                    biblist.append(b_str)                                
                    i = linelength - 1                                   
                i = i + 1                                                
elif backend == "bibtex":
    auxfile = open(auxname, 'r', encoding='latin-1')
#    auxfile = open(auxname, 'r', encoding='utf-8')
    lines = auxfile.readlines()
    for linei in range(len(lines)):
        str1 = lines[linei]
        i = 0
        linelength = len(str1)
        while i != linelength:
            b = re.findall(r'\\bibdata{([-_,a-zA-Z\d]+)}', str1[i:])
            if b:
                b_list = ''.join(b).split(",")
                for k in range(len(b_list)):
                    if k > 0:
                        biblist.append(''.join(b_list[k]) + ".bib")
                i = linelength - 1
            i = i + 1   
            
if citenum == 1:            ## if there is no citation in the document, citenum = 0   

    curdir = os.getcwd()                                                                                                  

    # Searching bib file from BIBINPUTS path (bibinputs_list)                                                             
    #                                                                                                                     
    # .bib may come from current directory, or environment variable,                                                      
    #   or BIBINPUTS in cwtex.ini                                                                                         
                                                                                                                          
    # subdir = ""                                                                                                         
    # curdir = os.getcwd()                                                                                                
    #                                                                                                                     
    # config = configparser.ConfigParser()                                                                                
    # config.sections()                                                                                                   
    # cwtexini = os.path.join(sys.path[0], "cwtex.ini")                                                                   
    #                                                                                                                     
    # if os.environ.get('BIBINPUTS') is None:                                                                             
    #     new_env =  curdir                                                                                               
    # else:                                                                                                               
    #     new_env = os.environ.get('BIBINPUTS') + ';' + curdir + ';' + ori_curdir                                         
    #                                                                                                                     
    # if config.read(cwtexini):                                                                                           
    #     if config['paths']['BIBINPUTS'] != '':                                                                          
    #         new_env = config['paths']['BIBINPUTS'] + ';' + new_env                                                      
    # os.environ['BIBINPUTS'] = new_env                                                                                   
    #                                                                                                                     
    # BIBINPUTS was expanded in cwpdf.py                                                                                  
                                                                                                                          
    new_env = os.environ['BIBINPUTS']                                                                                     
                                                                                                                          
    bibinputs_list = new_env.replace(".:", "").replace("//:", "").replace("//", "").replace(":/", ";/").split(";")        
                                                                                                                          
    backupbib=[]                                                                                                          
    delbackup=[]                                                                                                          
    deltmpbib=[]                                                                                                          
    delsearbib=[]                                                # 20170410                                               
    for i in range(len(biblist)):                                # Checking all .bib files                                
        nbib = biblist[i].split('.')                                                                                      
        if os.path.isfile(biblist[i]):                           #                                                        
            shutil.copy(biblist[i], nbib[0] + '-backup.bib' )    #                                                        
            shutil.copy(biblist[i], nbib[0] + '-tmp.bib' )                                                                
            delbackup.append(nbib[0] + '-backup.bib')                                                                     
            backupbib.append(nbib[0])                                                                                     
            deltmpbib.append(nbib[0])                                                                                     
            cvtc(nbib[0], zhuyinon)                                                                                       
            print(biblist[i] + ' found in the working directory.')                                                       
        else :                                                                                                            
            j=0                                                # search for .bib from bibinputs_list                      
            print(biblist[i] + ' not in the working directory, so search for it.')                                              
            print(bibinputs_list)                                                                                         
            for j in range(len(bibinputs_list)):                                                                          
                f = os.path.join(bibinputs_list[j],  biblist[i])                                                          
                if os.path.isfile(f):                                                                                     
                    delsearbib.append(nbib[0] + '.bib')     # 4/10                                                        
                    curname = os.path.join(curdir, nbib[0] + '-tmp.bib')                                                  
                    shutil.copy(f, curname)                                                                               
                    deltmpbib.append(nbib[0])                                                                             
                    cvtc(nbib[0], zhuyinon)                                                                               
                    # cvtc(nbib[0])                                                                                       
            if not os.path.exists(os.path.join(curdir, nbib[0] + '-tmp.bib')):                                            
                print("Can not find " + biblist[i] + ", so bibliography will not be shown.")                    
                                                                                                                          
    from subprocess import call                                                                                           
                                                                                                                          
    if backend == "biber":                                                                                                
        print("using biber")                                                                                              
        call(["biber", "-E", "ascii", basename])                          ## NB. this is important,                       
    elif backend == "bibtex":                                             ## otherwise \=o will be translated to UTF-8    
        print("using bibtex")                                                                                             
        call(["bibtex8", "-c", "ascii.csf", "-W", basename])                                                              
                                                                                                                          
    filebbl = basename + '.bbl'                                                                                           
    filetmp = 'temp21-tmp.bbl'                                                                                            
    cvte(filebbl,filetmp)                                                                                                 
                                                                                                                          
    cwtexpy = os.path.join(sys.path[0], "cwtex51b.py")                                                                    
                                                                                                                          
    if engine == "luatex":                                                                                                
        from subprocess import call                                                                                       
        try:                                                                                                              
            call(["python", cwtexpy, filetmp, "-a", "-x", "-o", filebbl])           # for windows                           
        except OSError:                                                                                                   
            call(["python3", cwtexpy, filetmp, "-a", "-x", "-o", filebbl])        # for mac                               
    elif engine == "pdftex":                                                                                              
        from subprocess import call                                                                                       
        try:                                                                                                              
            call(["python", cwtexpy, filetmp, "-a", "-x", "-l", "-o", filebbl])           # for windows                     
        except OSError:                                                                                                   
            call(["python3", cwtexpy, filetmp, "-a", "-x", "-l", "-o", filebbl])        # for mac     
            
### for 3 author and the first ends with \cH33

    with open(filebbl) as f:
        newText=f.read().replace('\\cH33}},\n', '\\cH33}\\hphantom{}},\n')

    with open(filebbl, "w") as f:
        f.write(newText)
###         
                                                                                                                          
    changecw()                                                                                                            
    print('changecw done.')                                                                                               
                                                                                                                          
    for i in range(len(backupbib)):                                                                                       
        backf = backupbib[i] + "-backup.bib"                                                                              
        bibf = backupbib[i] + ".bib"                                                                                      
        shutil.copy(backf, bibf)                                                                                          
                                                                                                                          
    for i in range(len(delbackup)):                                                                                       
        delbackf = delbackup[i]                                                                                           
        try:                                                                                                              
            os.remove(delbackf)  # os.remove(deltmpf)                                                                     
        except OSError:                                                                                                   
            pass                                                                                                          
                                                                                                                          
    for i in range(len(deltmpbib)):                                                                                       
        deltmpf = deltmpbib[i] + "-tmp.bib"                                                                               
        try:                                                                                                              
            os.remove(deltmpf)                                                                                            
        except OSError:                                                                                                   
            pass                                                                                                          
                                                                                                                          
    try:                                                                                                                  
        os.remove("temp21-tmp.bbl")                                                                                       
    except OSError:                                                                                                       
        pass                                                                                                              
                                                                                                                          
    print('[' + str(linei+1) + ']')                                                                                       
                                                                                                                          
    for i in range(len(delsearbib)):                   # 20170410                                                         
        delsearf = delsearbib[i]                                                                                          
        try:                                                                                                              
            os.remove(delsearf)                                                                                           
        except OSError:                                                                                                   
            pass                                                                                                          
                                                                                                                          
    # file.close()                                                                                                        
    # file_object.close()                                                                                                 




