#!/usr/bin/python

#--------------------------------------------------------------------------------------------------------
# This python file is used for processing a complete book.
# It assumes that there is a folder named 'input' that contains all input images
# 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
# You also need a book_settings.py that store all book specific settings.
#
# To scan a book, start with all the right hand pages from the start to the end, then take all left hand pages
# When starting over with the left hande page, its important to start with the same spread (page-pair) as the right-hand.
# 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

# All the dynamic (book specific) settings are store in an external python-file.
# This makes it easier to share this file while maintaining multiple settings-files.
from book_settings import *

#--------------------------------------------------------------------------------------------------------
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)

# Check that there is an input folder
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 (*.jpg) in the input folder and sort them according to their name
#           The list contains complete full path filenames
pics = sorted([os.path.join(ipath, pic)
               for pic in os.listdir(ipath)
               if pic.endswith(image_post_name) and os.path.isfile(os.path.join(ipath, pic))])

# --------- Create the lists that will contain the left and right hand pages
rHandSides = []
lHandSides = []
covFilePath = ''    # Full path filename of the cover image
refFilePath = ''    # Full path filename of the reference image

# --------- Loop through all images in "raw" image list and put them into two lists, one for right pages and one for left
#           When we get to the image with the number that matches firstLeftHandPage, then we switch to adding files to that left-list instead
addFilesToRightList = True  # If we should add images to the right-hand page list (at the beginning)
for ifile in pics:
    imgNoStartPos = ifile.find(image_pre_name)+len(image_pre_name)  # Get start pos of the number portion
    imgNumber = int( ifile[imgNoStartPos:imgNoStartPos+numberNumericalsInName] ) # Int containing the numberical part of the image-name
    # Check if it's the cover image or reference image
    if covFilePath == '' and imgNumber == coverImage:
        covFilePath = ifile
        print( 'Cover file:' + ifile )
    elif refFilePath == '' and imgNumber == refImg:
        refFilePath = ifile
        print( 'Reference file:' + ifile )
    else:
        if addFilesToRightList == True and imgNumber >= firstLeftHandPage:
            addFilesToRightList=False

        if addFilesToRightList == True:
            rHandSides.append( ifile )
        else:
            lHandSides.append( ifile )
        
# ------ Check that we have found both ref-file and cover-file    
if refFilePath == '' or covFilePath == '':
    print('ERROR: Missing cover or reference image')
    exit()

# ------ Now it's time to create the white and black reference files.
#        They are created in the root-folder of the project so we need to move them to temp-folder
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 )

leftPageNo = pageNoOfFirstLeftPage      # Start page-number for left and right output pages
rightPageNo = pageNoOfFirstLeftPage+1

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.bmp' + \
                ' -wref ' + tpath + '/ref_white.jpg' + \
                ' -bref ' + tpath + '/ref_black.jpg' + \
                ' -s ' + settingsFile , shell=True)

# Rotate the image and store it in the final position (output-folder)
subprocess.call( 'sips -r 270 -s dpiHeight 200.0 -s dpiWidth 200.0 temp/temp.bmp --out ' + opath + '/page_'+str(1).zfill(numberNumericalsInName)+'.bmp ', shell=True)


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

    # Rotate the image
    subprocess.call( 'sips -r 90 -s dpiHeight 200.0 -s dpiWidth 200.0 temp/temp.bmp --out ' + opath + '/page_'+str(leftPageNo).zfill(numberNumericalsInName)+'.bmp ', shell=True)


    leftPageNo = leftPageNo + 2 # Increase the page conter

# Continue with the rest of the right hand pages
for i in range( len(rHandSides) ):    
    
    # Right page after. Process it
    print( '---------- Processing right-hand page: ' + str(rightPageNo) + ' --- File: '+rHandSides[i]+'----------' )
    subprocess.call('../PageNormalizer/build-Mac/PageNormalizer ' + \
                    ' -q ' \
                    ' -i ' + rHandSides[i]  + \
                    ' -o ' + tpath+'/temp.bmp' + \
                    ' -wref ' + tpath + '/ref_white.jpg' + \
                    ' -bref ' + tpath + '/ref_black.jpg' + \
                    ' -s ' + settingsFile , shell=True)

    # Rotate the image
    subprocess.call( 'sips -r 270 -s dpiHeight 200.0 -s dpiWidth 200.0 temp/temp.bmp --out ' + opath + '/page_'+str(rightPageNo).zfill(numberNumericalsInName)+'.bmp ', shell=True)
    
    rightPageNo = rightPageNo + 2 # Increase the page conter
    
