#!/usr/bin/env python
# -*- encoding: utf-8 -*-

# Copyright (c) 2012, tamanegi (tamanegi@users.sourceforge.jp)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

import sys
import numpy as np
import os

filedirname = os.path.dirname( os.path.abspath( __file__ ) )
commonpath = os.path.join( filedirname, "../common" )
if not commonpath in sys.path:
  sys.path.append( commonpath )
from vector3d import *

class MacMolPltOut:
  def __init__( self, filename = "" ):
    self.__initializeValues()
    if len( filename ) > 0:
      self.read( filename )

  def __initializeValues( self ):
    self.__gridnum = Vector3D( 0, 0, 0 )
    self.__gridsize = Vector3D( 0, 0, 0 )
    self.__origin = Vector3D( 0, 0, 0 )
    self.__container = np.array( [], dtype=float )

  def getGridData( self ):
    return self.__container

  def getGridNum( self ):
    return self.__gridnum

  def getGridSize( self ):
    return self.__gridsize

  def getCellOrigin( self ):
    return self.__origin

  def read( self, filename ):
    if len(filename) == 0:
      return
    try:
      fh = open( filename, "r" )
    except IOError, ( errno, msg ):
      print >> sys.stderr, "Error: cannot open %s for reading." % filename
      print >> sys.stderr, "Error: errno = [%d] msg = [%s]" % ( errno, msg )
      sys.exit(1)

    line = fh.readline() # title?
    self.checkDataType( line )

    line = fh.readline() # grid number
    sline = line.split()
    if len( sline ) < 3:
      print >> sys.stderr, "Error: cannot read grid numbers."
      sys.exit(2)
    self.__gridnum = Vector3D( int( sline[0] ), int( sline[1] ), int( sline[2] ) )
    line = fh.readline() # cell origin
    sline = line.split()
    if len( sline ) < 3:
      print >> sys.stderr, "Error: cannot read cell origin."
      sys.exit(3)
    self.__origin = Vector3D( float( sline[0] ), float( sline[1] ), float( sline[2] ) )

    line = fh.readline() # distance between cells
    sline = line.split()
    if len( sline ) < 3:
      print >> sys.stderr, "Error: cannot read cell distance."
      sys.exit(4)
    self.__gridsize = Vector3D( float( sline[0] ), float( sline[1] ), float( sline[2] ) )

    data = []
    line = fh.readline()
    while line:
      sline = line.split()
      for val in sline:
        data.append( val )
      line = fh.readline()

    counter = 0
    self.__container.resize( ( self.__gridnum.x, self.__gridnum.y, self.__gridnum.z ) )
    self.__container.fill( 0.0 )
    for i in range( 0, self.__gridnum.x ):
      for j in range( 0, self.__gridnum.y ):
        for k in range( 0, self.__gridnum.z ):
          self.__container[i][j][k] = data[counter]
          counter += 1

  def checkDataType( self, line ):
    sline = line.split()
    if sline[0] != "3D" or sline[1] != "Orbital":
      print >> sys.stderr, "WARNING: is this file an output from MacMolPlt?"
