require "narray_yaml"
require "numru/gphys"
require "numru/netcdf"

class Variable < NodeEntityAbstract

  has_many :diagram_caches, :through => :diagram_cache_data, :source => :diagram_cache
  has_many :diagram_cache_data, :dependent => :destroy
  has_many :actual_files, :dependent => :destroy
  has_many :knowledge_figures

  after_create :save_references


  def vname
    if vn = node.file
      return node.path.sub(/#{vn}\//,"")
    else
      return name
    end
  end

  def fname
    if node.file
      node.add_prefix(node.file)
    elsif (acs = actual_files).length > 0
      acs.collect{|ac| node.add_prefix(ac.path) }
    else
      raise "[BUG]"
    end
  end

  def gphys
    NumRu::GPhys::IO.open(fname, vname)
  end

  def references_tmp
    unless @new_record
      raise "Cannot #call references_tmp for saved data. Use references instead"
    end
    @references_tmp ||= Array.new
  end

  def downloadable?
    if parent
      return parent.entity.downloadable?
    else
      da = true
      references_tmp.each{|v|
        unless v.downloadable?
          da = false
          break
        end
      }
      return da
    end
  end


  protected
  def save_references
    if @references_tmp
      @references_tmp.each{|v|
        v = v.node unless Node === v
        NodeRelation.new(:name=>"analysis", :reference=>v, :referenced_by=>self.node).save!
      }
    end
  end

  def self.knowledges(user, path)
    knowledge_ids = []
    variable = Variable.find(:first, :conditions => [ "path = ?", path ], :user => user)
    knowledge_figures = KnowledgeFigure.find(:all, {:conditions => ["variable_id = ?", variable.id]})
      
    for kf in knowledge_figures
      knowledge_ids.push(Knowledge.find(:first, :conditions => ["id = ?", kf.knowledge_id], :user => user).id)
    end
    knowledge_ids.uniq!
    return knowledge_ids
  end

end
