# -*- coding: utf-8 -*-
# This file is part of SimpleMath, a lightweight C++ template library
# for linear algebra.
#
# Copyright (C) 2009 Benjamin Schindler <bschindler@inf.ethz.ch>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

# Pretty printers for SimpleMath::Matrix
# This is still pretty basic as the python extension to gdb is still pretty basic.
# It cannot handle complex simplemath types and it doesn't support many of the other simplemath types
# This code supports fixed size as well as dynamic size matrices

# To use it:
#
# * Create a directory and put the file as well as an empty __init__.py in
#   that directory.
# * Create a ~/.gdbinit file, that contains the following:
#      python
#      import sys
#      sys.path.insert(0, '/path/to/simplemath/printer/directory')
#      from printers import register_simplemath_printers
#      register_simplemath_printers (None)
#      end

import gdb
import re
import itertools
from bisect import bisect_left

# Basic row/column iteration code for use with Sparse and Dense matrices
class _MatrixEntryIterator(object):

	def __init__ (self, rows, cols):
		self.rows = rows
		self.cols = cols
		self.currentRow = 0
		self.currentCol = 0

	def __iter__ (self):
		return self

	def next(self):
		return self.__next__()  # Python 2.x compatibility

	def __next__(self):
		row = self.currentRow
		col = self.currentCol
		if self.currentRow >= self.rows:
			raise StopIteration

		self.currentCol = self.currentCol + 1
		if self.currentCol >= self.cols:
			self.currentCol = 0
			self.currentRow = self.currentRow + 1

		return (row, col)

class SimpleMathMatrixPrinter:
	"Print SimpleMath Matrix or Array of some kind"

	def __init__(self, variety, val):
		"Extract all the necessary information"

		# Save the variety (presumably "Matrix" or "Array") for later usage
		self.variety = variety

		# The gdb extension does not support value template arguments - need to extract them by hand
		type = val.type
		if type.code == gdb.TYPE_CODE_REF:
			type = type.target()
		self.type = type.unqualified().strip_typedefs()
		tag = self.type.tag
		regex = re.compile('\<.*\>')
		m = regex.findall(tag)[0][1:-1]
		template_params = m.split(',')
		template_params = [x.replace(" ", "") for x in template_params]

		self.rows = 3 
		self.cols = 1
		self.innerType = self.type.template_argument(0)
		print ("type: ", str(self.type))
		self.data = val['mStorage']['mData']
#		self.rows = val['mStorage']['mRows']
#		self.cols = val['mStorage']['mCols']
#
#		self.innerType = self.type.template_argument(0)
#
#		self.val = val
#
#		# Fixed size matrices have a struct as their storage, so we need to walk through this
#		self.data = self.val['mStorage']['mData']
#		if self.data.type.code == gdb.TYPE_CODE_STRUCT:
#			self.data = self.data['array']
#			self.data = self.data.cast(self.innerType.pointer())

	class _iterator(_MatrixEntryIterator):
		def __init__ (self, rows, cols, dataPtr):
			super(SimpleMathMatrixPrinter._iterator, self).__init__(rows, cols)

			self.dataPtr = dataPtr

		def __next__(self):

			row, col = super(SimpleMathMatrixPrinter._iterator, self).__next__()

			item = self.dataPtr.dereference()
			self.dataPtr = self.dataPtr + 1
			if (self.cols == 1): #if it's a column vector
				return ('[%d]' % (row,), item)
			elif (self.rows == 1): #if it's a row vector
				return ('[%d]' % (col,), item)
			return ('[%d,%d]' % (row, col), item)

	def children(self):

		return self._iterator(self.rows, self.cols, self.data)

	def to_string(self):
		return "SimpleMath::%s<%s,%d,%d,%s> (data ptr: %s)" % (self.variety, self.innerType, self.rows, self.cols, self.data)

def build_simplemath_dictionary ():
	pretty_printers_dict[re.compile('^SimpleMath::MatrixBase<.*>$')] = lambda val: SimpleMathMatrixPrinter("Matrix", val)
	print(str(pretty_printers_dict))

def register_simplemath_printers(obj):
	"Register simplemath pretty-printers with objfile Obj"

	if obj == None:
		obj = gdb
	obj.pretty_printers.append(lookup_function)

def lookup_function(val):
	"Look-up and return a pretty-printer that can print va."

	type = val.type

	if type.code == gdb.TYPE_CODE_REF:
		type = type.target()
	type = type.unqualified().strip_typedefs()

	typename = type.tag
	if typename == None:
		return None

	for function in pretty_printers_dict:
		if function.search(typename):
			return pretty_printers_dict[function](val)

	return None

pretty_printers_dict = {}

build_simplemath_dictionary ()

