import argparse
import subprocess
import ntpath
import tempfile
import shutil

parser = argparse.ArgumentParser(description='Compile to SPIRV and generate header/implementation')
parser.add_argument('files', metavar='files', nargs='+', help='list of glsl files')
parser.add_argument('--output', action='store', dest='output', help='output file')
parser.add_argument('--compiler', action='store', dest='compiler', help='location of spirv compiler')
parser.add_argument('--vulkan_version', action='store', dest='version', help='vulkan version')

args = parser.parse_args()

# create temp dir
dirpath = tempfile.mkdtemp()

def genCArray(file):
  basename = ntpath.basename(file).replace('.', '_')
  temp_file = dirpath + '/' + basename + '.txt'
  try:
    subprocess.check_output([args.compiler,'--target-env', 'vulkan' + args.version, '-V',file,'-x','-o',temp_file]).decode('utf-8')
  except subprocess.CalledProcessError as e:
    print(e.output)
  content = None
  with open(temp_file, 'r') as content_file:
    content = content_file.read()
  array = 'const uint32_t _' + basename + '[] = {\n' + content + '\n};\n'
  spirv = 'Vortex::Renderer::SpirvBinary ' + basename + '(_' + basename + ');\n'
  return array + spirv

def genCArrayDef(file):
  basename = ntpath.basename(file).replace('.', '_')
  return 'extern Vortex::Renderer::SpirvBinary ' + basename + ';\n'

output = ntpath.basename(args.output)

with open(args.output + '.h', 'w') as f:
  f.write('/* This header is autogenerated */\n')
  f.write('#ifndef GENERATED_' + output.upper() +'_H\n')
  f.write('#define GENERATED_' + output.upper() + '_H\n\n')
  f.write('''#include <cstdint>

namespace Vortex
{
namespace Renderer
{
class SpirvBinary;
}

namespace SPIRV
{
''')

  for file in args.files:
    f.write(genCArrayDef(file))

  f.write('''
}
}

#endif

''')

with open(args.output + '.cpp', 'w') as f:
  f.write('''/* This header is autogenerated */

#include <Vortex/Renderer/Device.h>
''')
  f.write('#include "' + ntpath.basename(args.output) +  '.h"\n\n')
  f.write('''

namespace Vortex
{
namespace SPIRV
{
''')

  for file in args.files:
    f.write(genCArray(file))

  f.write('''
}
}

''')

# remove temp dir
shutil.rmtree(dirpath)
