// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.

#ifndef tools_wroot_leaf
#define tools_wroot_leaf

#include "base_leaf"

namespace tools {
namespace wroot {

inline const std::string& leaf_store_class(char) {
  static const std::string s_v("TLeafB");
  return s_v;
}
inline const std::string& leaf_store_class(short) {
  static const std::string s_v("TLeafS");
  return s_v;
}
inline const std::string& leaf_store_class(int) {
  static const std::string s_v("TLeafI");
  return s_v;
}
inline const std::string& leaf_store_class(float) {
  static const std::string s_v("TLeafF");
  return s_v;
}
inline const std::string& leaf_store_class(double) {
  static const std::string s_v("TLeafD");
  return s_v;
}

template <class T>
class leaf : public base_leaf {
public: //ibo
  virtual const std::string& store_cls() const {
    return leaf_store_class(T());
  }
  virtual bool stream(buffer& a_buffer) const {
    unsigned int c;
    if(!a_buffer.write_version(1,c)) return false;
    if(!base_leaf::stream(a_buffer)) return false;
    if(!a_buffer.write(m_min)) return false;
    if(!a_buffer.write(m_max)) return false;
    if(!a_buffer.set_byte_count(c)) return false;
    return true;
  }
public: //base_leaf
  virtual bool fill_basket(buffer& a_buffer) const {
    return a_buffer.write<T>(m_value);
  }
public:
  leaf(std::ostream& a_out,
              wroot::branch& a_branch,
              const std::string& a_name,
              const std::string& a_title)
  : base_leaf(a_out,a_branch,a_name,a_title)
  ,m_min(T()),m_max(T())
  ,m_value(T())
  {
    m_length = 1;
    m_length_type = sizeof(T);
  }
  virtual ~leaf(){}
protected:
  leaf(const leaf& a_from): base_leaf(a_from){}
  leaf& operator=(const leaf&){return *this;}
public:
  void fill(const T& a_value) {m_value = a_value;}
protected:
  T m_min;    //Minimum value if leaf range is specified
  T m_max;    //Maximum value if leaf range is specified
  T m_value;
};

}}

#endif
