#!/usr/bin/env python

"""
  This file is part of Road Hog Newgrf for OpenTTD.
  Road Hog 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, version 2.
  Road Hog 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 Road Hog. If not, see <http://www.gnu.org/licenses/>.
"""
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, logging
logger = multiprocessing.log_to_stderr()
logger.setLevel(25)

import road_hog
import utils
import global_constants

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(items):
    variant = items[0]
    consist = items[1]
    if variant.graphics_processor is None:
        shutil.copy(os.path.join(graphics_input, variant.get_spritesheet_name(consist)), graphics_output_path)
    else:
        result = variant.graphics_processor.pipeline.render(variant, consist)
        return result

# wrapped in a main() function so this can be called explicitly, because unexpected multiprocessing fork bombs are bad
def main():
    consists = road_hog.get_consists_in_buy_menu_order()
    variants = []
    for consist in consists:
        spritesheet_suffixes_seen = []
        for variant in consist.model_variants:
            # raise if spritesheet_suffix number is a duplicate
            if variant.spritesheet_suffix in spritesheet_suffixes_seen:
                raise AssertionError("Duplicate spritesheet suffix in consist " + consist.id + ": " + str(variant.spritesheet_suffix))
            else:
                spritesheet_suffixes_seen.append(variant.spritesheet_suffix)
            variants.append((variant, consist))

    pool = Pool(processes=16)
    pool.map(run_pipeline, variants)
    pool.close()
    pool.join()

if __name__ == '__main__':
    main()
