#!/usr/bin/python

#--------------------------------------------------------------------------------------------------------
# This python file is processing a complete book
# It assumes that there is a folder named 'input' that contains all input data
# The output is generated into a folder called 'output'
# A folder called 'temp' is also used for intermediate files (that can be cleaned later)
# In the 'input'-folder, there should only be image-files ending with a jpg-file-extension
#
# To scan a book, start with all the right hand pages from the start to the end, then take all left hand pages
# The number of right/left-pages must be equal
#
# The reference image and cover image can be taken in any order, but must be pointed out below in the 'arguments'
#
# Static Input arguments. 
ipath = './input'
opath = './output'
tpath = './temp'
settingsFile = tpath + '/' + 'settings.txt'
image_pre_name = 'img_'         # The part of the filename before the numerical part
image_post_name = '.jpg'        # Part of the filename after the numerical part
numberNumericalsInName=4        # Number of numericals in file name-index. For example 4 in 0304 and 1234

# Dynamic Input arguments. These very for every book that is scanned and for every scan
refImg = 100                    # The image used as reference image
coverImage = 238.               # Image used for cover (Will be placed 1st)
firstLeftHandPage = 237         # The first image covering the left pages
cropX1 = 250                    # Crop coordinates of all the images
cropY1 = 38
cropX2 = 3673
cropY2 = 2685

#--------------------------------------------------------------------------------------------------------
import os
import subprocess
import shutil

# Do some clean-up first of folders
shutil.rmtree(tpath, ignore_errors=True)
shutil.rmtree(opath, ignore_errors=True)
#subprocess.call('rm -rf ' + tpath)
#subprocess.call('rm -rf ' + opath)

# Create output folders, if they don't exist
if not os.path.exists(opath): os.makedirs(opath)
if not os.path.exists(tpath): os.makedirs(tpath)

if not os.path.exists(ipath):
    print('ERROR: No input folder !')
    exit()
    
# Create the settings.txt-file (Used for imgage-cropping)
file = open(settingsFile,'w') 
file.write('# Autogenerated file.\nSTART:\n' + str(cropX1) + '\n' + str(cropY1) + '\n' + str(cropX2) + '\n' + str(cropY2) + '\n')
file.close()

# Loop through all images in the input folder and put them into two lists, one for right pages and one for left
pics = sorted([os.path.join(ipath, pic)
               for pic in os.listdir(ipath)
               if pic.endswith('.jpg') and os.path.isfile(os.path.join(ipath, pic))])

rHandSides = []
lHandSides = []
covFile = image_pre_name + str(int(coverImage)).zfill(numberNumericalsInName) + image_post_name
refFile = image_pre_name + str(int(refImg)).zfill(numberNumericalsInName) + image_post_name
covFilePath = ''
refFilePath = ''

for ifile in pics:
    imgNoStartPos = ifile.find(image_pre_name)+len(image_pre_name)
    imgNumber = int( ifile[imgNoStartPos:imgNoStartPos+numberNumericalsInName] )
    # Check if it's the cover image or reference image
    if ifile.find( covFile ) > 0:
        covFilePath = ifile
        print( 'Cover file:' + ifile )
    elif ifile.find( refFile ) > 0:
        refFilePath = ifile
        print( 'Reference file:' + ifile )
    elif imgNumber < firstLeftHandPage:
        rHandSides.append( imgNumber )
    elif imgNumber >= firstLeftHandPage:
        lHandSides.append( imgNumber )
        
if len(rHandSides) != len(lHandSides):
    print('Error: Number of left and right hand sides must be equal. Left:' + str(len(lHandSides)) + ' Right:'+ str(len(rHandSides)) )
    exit()
    
if refFilePath == '' or covFilePath == '':
    print('ERROR: Missing cover or reference image')
    exit()

print( '---------- Creating reference files ----------' )
subprocess.call('../RefImageCreator/build-Mac/RefImageCreator -i ' + refFilePath, shell=True)

# Move ref-files to the temp-folder
shutil.move('./ref_black.jpg', tpath )
shutil.move('./ref_white.jpg', tpath )

pageNo = 1      # Page-number for output pages

print( '---------- Processing cover page  ----------' )

# First convert the cover-page as it should be number one
subprocess.call('../PageNormalizer/build-Mac/PageNormalizer ' + \
                ' -i ' + covFilePath + \
                ' -o ' + tpath+'/temp.jpg' + \
                ' -wref ' + tpath + '/ref_white.jpg' + \
                ' -bref ' + tpath + '/ref_black.jpg' + \
                ' -s ' + settingsFile , shell=True)

# Rotate the image
subprocess.call('jpegtran -rotate 90 -outfile ' + opath + '/page_'+str(pageNo).zfill(numberNumericalsInName)+'.jpg ' + tpath+'/temp.jpg', shell=True)

# Increase the page conter
pageNo = pageNo + 1

# Start doing the rest of the pages. Left pages first and then the right page
for i in range( len(lHandSides) ):    
    
    # Left page first. Process it
    print( '---------- Processing left-hand page: ' + str(pageNo) + ' ----------' )
    subprocess.call('../PageNormalizer/build-Mac/PageNormalizer ' + \
                    ' -i ' + ipath + '/' + image_pre_name + str(lHandSides[i]).zfill(numberNumericalsInName) + image_post_name  + \
                    ' -o ' + tpath+'/temp.jpg' + \
                    ' -wref ' + tpath + '/ref_white.jpg' + \
                    ' -bref ' + tpath + '/ref_black.jpg' + \
                    ' -s ' + settingsFile , shell=True)

    # Rotate the image
    subprocess.call('jpegtran -rotate 90 -outfile ' + opath + '/page_'+str(pageNo).zfill(numberNumericalsInName)+'.jpg ' + tpath+'/temp.jpg', shell=True)


    pageNo = pageNo + 1 # Increase the page conter
    
    # Right page after. Process it
    print( '---------- Processing right-hand page: ' + str(pageNo) + ' ----------' )
    subprocess.call('../PageNormalizer/build-Mac/PageNormalizer ' + \
                    ' -i ' + ipath + '/' + image_pre_name + str(rHandSides[i]).zfill(numberNumericalsInName) + image_post_name  + \
                    ' -o ' + tpath+'/temp.jpg' + \
                    ' -wref ' + tpath + '/ref_white.jpg' + \
                    ' -bref ' + tpath + '/ref_black.jpg' + \
                    ' -s ' + settingsFile , shell=True)

    # Rotate the image
    subprocess.call('jpegtran -rotate 270 -outfile ' + opath + '/page_'+str(pageNo).zfill(numberNumericalsInName)+'.jpg ' + tpath+'/temp.jpg', shell=True)
    
    pageNo = pageNo + 1 # Increase the page conter
    
    
