#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# AWL simulator - Symbol table parser
#
# Copyright 2014-2016 Michael Buesch <m@bues.ch>
#
# This program 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; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

from __future__ import division, absolute_import, print_function, unicode_literals

import sys
import getopt

from awlsim_loader.common import *
from awlsim_loader.core import *


def usage():
	print("awlsim-symtab symbol table parser, version %s" %\
		  VERSION_STRING)
	print("")
	print("Usage: awlsim-symtab [OPTIONS] [inputfile] [outputfile]")
	print("")
	print("If inputfile is - or omitted, stdin is used.")
	print("If outputfile is - or omitted, stdout is used.")
	print("")
	print("Options:")
	print(" -I|--input-format FMT     Input file format.")
	print("                           FMT may be one of: auto, csv, asc")
	print("                           Default: auto")
	print(" -O|--output-format FMT    Input file format.")
	print("                           FMT may be one of: csv, readable-csv, asc")
	print("                           Default: readable-csv")
	print("")
	print("Example usage for converting .ASC to readable .CSV:")
	print(" awlsim-symtab -I asc -O readable-csv symbols.asc symbols.csv")

def main():
	opt_inputParser = None
	opt_outputFormat = "readable-csv"
	opt_infile = "-"
	opt_outfile = "-"

	try:
		(opts, args) = getopt.getopt(sys.argv[1:],
			"hI:O:",
			[ "help", "input-format=", "output-format=", ])
	except getopt.GetoptError as e:
		printError(str(e))
		usage()
		return ExitCodes.EXIT_ERR_CMDLINE
	for (o, v) in opts:
		if o in ("-h", "--help"):
			usage()
			return ExitCodes.EXIT_OK
		if o in ("-I", "--input-format"):
			if v.lower() == "auto":
				opt_inputParser = None
			elif v.lower() in ("csv", "readable-csv"):
				opt_inputParser = SymTabParser_CSV
			elif v.lower() == "asc":
				opt_inputParser = SymTabParser_ASC
			else:
				printError("Invalid --input-format")
				return ExitCodes.EXIT_ERR_CMDLINE
		if o in ("-O", "--output-format"):
			opt_outputFormat = v.lower()
			if opt_outputFormat not in ("csv", "readable-csv", "asc"):
				printError("Invalid --output-format")
				return ExitCodes.EXIT_ERR_CMDLINE
	if len(args) == 1:
		opt_infile = args[0]
	elif len(args) == 2:
		opt_infile = args[0]
		opt_outfile = args[1]
	elif len(args) > 2:
		usage()
		return ExitCodes.EXIT_ERR_CMDLINE

	try:
		if opt_infile == "-":
			if isPy2Compat:
				inDataBytes = sys.stdin.read()
			else:
				inDataBytes = sys.stdin.buffer.read()
		else:
			inDataBytes = safeFileRead(opt_infile)

		# Decode the symbol table using S7 compatible encoding.
		encoding = SymTabSource.COMPAT_ENCODING
		try:
			inDataText = inDataBytes.decode(encoding)
		except UnicodeError as e:
			raise AwlSimError("Failed to %s decode symbol table text: "
				"%s" % (encoding, str(e)))

		if opt_inputParser:
			tab = opt_inputParser.parseText(inDataText,
							autodetectFormat=False)
		else:
			tab = SymTabParser.parseText(inDataText,
						     autodetectFormat=True)

		if opt_outputFormat == "csv":
			outDataText = tab.toCSV()
		elif opt_outputFormat == "readable-csv":
			outDataText = tab.toReadableCSV()
		elif opt_outputFormat == "asc":
			outDataText = tab.toASC(stripWhitespace=False)
		else:
			assert(0)

		# Encode the symbol table using S7 compatible encoding.
		encoding = SymTabSource.COMPAT_ENCODING
		try:
			outDataBytes = outDataText.encode(encoding)
		except UnicodeError as e:
			raise AwlSimError("Failed to %s encode symbol table text: "
				"%s" % (encoding, str(e)))

		if opt_outfile == "-":
			if isPy2Compat:
				sys.stdout.write(outDataBytes)
				sys.stdout.flush()
			else:
				sys.stdout.buffer.write(outDataBytes)
				sys.stdout.buffer.flush()
		else:
			try:
				fd = open(opt_outfile, "wb")
				fd.write(outDataBytes)
				fd.close()
			except IOError as e:
				printError("Failed to write output file '%s': %s" %\
					   (opt_outfile, str(e)))
				return ExitCodes.EXIT_ERR_IO
	except AwlSimError as e:
		printError(e.getReport())
		return ExitCodes.EXIT_ERR_SIM
	return ExitCodes.EXIT_OK

if __name__ == "__main__":
	sys.exit(main())
