print("[RENDER GRAPHICS] render_graphics.py")

import codecs # used for writing files - more unicode friendly than standard open() module

import shutil
import sys
import os
currentdir = os.curdir
from multiprocessing import Pool
import multiprocessing
logger = multiprocessing.log_to_stderr()
logger.setLevel(25)
from time import time

import road_hog
import utils
import global_constants

# get args passed by makefile
makefile_args = utils.get_makefile_args(sys)
num_pool_workers = makefile_args.get('num_pool_workers', 0) # default to no mp, makes debugging easier (mp fails to pickle errors correctly)
if num_pool_workers == 0:
    use_multiprocessing = False
    print('Multiprocessing disabled: (PW=0)') # just print, no need for a coloured echo_message
else:
    use_multiprocessing = True
    print('Multiprocessing enabled: (PW=' + str(num_pool_workers) + ')') # just print, no need for a coloured echo_message

graphics_input = os.path.join(currentdir, 'src', 'graphics')
graphics_output_path = os.path.join(road_hog.generated_files_path, 'graphics')
if os.path.exists(graphics_output_path):
    shutil.rmtree(graphics_output_path)
os.mkdir(graphics_output_path)

hint_file = codecs.open(os.path.join(graphics_output_path, '_graphics_files_here_are_generated.txt'), 'w','utf8')
hint_file.write("Don't edit the graphics files here.  They're generated by the build script. \n Edit sources in graphics_sources and export spritesheets to graphics_input.")
hint_file.close()

def run_pipeline(consist):
    if consist.gestalt_graphics.pipeline is None:
        shutil.copy(os.path.join(graphics_input, consist.roster_id, consist.id + '.png'), graphics_output_path)
    else:
        result = consist.gestalt_graphics.pipeline.render(consist, global_constants)
        return result

# wrapped in a main() function so this can be called explicitly, because unexpected multiprocessing fork bombs are bad
def main():
    start = time()
    consists = road_hog.get_consists_in_buy_menu_order()

    if use_multiprocessing == False:
        for consist in consists:
            run_pipeline(consist)
    else:
        pool = Pool(processes=num_pool_workers)
        pool.map(run_pipeline, consists)
        pool.close()
    # eh, how long does this take anyway?
    print(format((time() - start), '.2f')+'s')

if __name__ == '__main__':
    main()
