
#
# (C) Copyright Broadcom Corporation 2012-2014
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#


class OpENUtil
	attr_accessor :client

  def initialize()
    @client = nil
  end

  def connect(appname)
    maxtries = 100
    handle = OpEN::OpenapiClientHandle_s.new
    ret = OpEN.openapiClientRegister(appname, handle)
    @client = handle
    if ret == OpEN::OPEN_E_NONE
      ret = OpEN.openapiConnectivityCheck(@client)
      count = 0
      while ret != OpEN::OPEN_E_NONE and count < maxtries
        count+=1
        sleep(1)
        ret = OpEN.openapiConnectivityCheck(@client)
      end
    end
    return ret
  end

  def getCharBuffer(size, init=nil)
    ret = OpEN::CharArray.new(size)
    if init != nil
      if init.length > size
        count = size
      else
        count = init.length
      end
      for x in 0..count-1
        ret[x] = init[x]
      end
      ret[count] = nil
    else
      for x in 0..size-1
        ret[x] = nil
      end
    end
    return ret
  end

  def getUCharBuffer(size, init=nil)
    ret = OpEN::UcharArray.new(size)
    if init != nil
      if init.length > size
        count = size
      else
        count = init.length
      end      
      for x in 0..count-1
        if init[x] != nil
          ret[x] = init[x]
        end
      end
      ret[count] = 0
    else
      for x in 0..size-1
        ret[x] = 0
      end
    end
    return ret
  end

  def getIntBuffer(size)
    ret = OpEN::IntArray.new(size)
    return ret
  end

  def getNetworkOSVersion()
    size = 100
    switch_os_revision_string = getCharBuffer(size, nil)
    switch_os_revision = OpEN::Open_buffdesc.new
    switch_os_revision.pstart = switch_os_revision_string
    switch_os_revision.size = size 
    ret = OpEN::openapiNetworkOSVersionGet(@client, switch_os_revision)
    if ret != OpEN::OPEN_E_NONE
      puts "Network OS version retrieve error"
    else
      printf "ICOS Version %s\n", switch_os_revision_string.cast()
    end
  end

  def getAPIVersion()
    revData = OpEN::Open_revision_data_t.new
    ret = OpEN::openapiApiVersionGet(@client, revData)
    if ret != OpEN::OPEN_E_NONE
      puts "OpEN version retrieve error"
    else
      printf "OpEN version = %u.%u.%u.%u\n", revData.release, revData.version, revData.maint_level, revData.build_num
    end
  end

  def terminate()
  end
end
