All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
DataEntityController.h
1 // Copyright (c) 2015 eeGeo. All rights reserved.
2 
3 #pragma once
4 
5 #include "Types.h"
6 #include <map>
7 #include <algorithm>
8 
9 namespace Eegeo
10 {
11  namespace Data
12  {
13  template <typename TArgs>
15  {
16  protected:
17  typedef typename TArgs::TId TId;
18  typedef typename TArgs::TModel TModel;
19  typedef typename TArgs::TView TView;
20  typedef typename TArgs::TViewFactory TViewFactory;
21  typedef typename TArgs::TRenderableFilter TRenderableFilter;
22 
23  typedef std::map<TModel*, TView*> TModelToView;
24 
25  public:
26  DataEntityController(TViewFactory& viewFactory, TRenderableFilter& renderableFilter)
27  : m_viewFactory(viewFactory)
28  , m_viewRenderer(renderableFilter)
29  {
30  }
31 
32  virtual ~DataEntityController()
33  {
34  for(typename TModelToView::iterator iter = m_modelToView.begin(); iter != m_modelToView.end(); ++iter)
35  {
36  TView* pView = iter->second;
37  m_viewRenderer.RemoveView(*pView);
38  m_viewFactory.FreeView(pView);
39  }
40  m_modelToView.clear();
41  }
42 
43  void Add(TModel& model)
44  {
45  TView* pView = m_viewFactory.CreateView(model);
46  m_viewRenderer.AddView(*pView);
47  m_modelToView[&model] = pView;
48  }
49 
50  void Remove(TModel& model)
51  {
52  Eegeo_ASSERT(
53  m_modelToView.find(&model) != m_modelToView.end(),
54  "Cannot remove, as it has not been added");
55 
56  TView* pView = m_modelToView[&model];
57 
58  m_modelToView.erase(&model);
59  m_viewRenderer.RemoveView(*pView);
60  m_viewFactory.FreeView(pView);
61  }
62 
63  struct HasId
64  {
65  HasId(const TId& id) : m_id(id) { }
66  bool operator() (const std::pair<TModel*, TView*>& pair) { return pair.first->GetId() == m_id; }
67  TId m_id;
68  };
69 
70  bool TryRemoveById(const TId& id, TModel*& out_removedItem)
71  {
72  typename std::map<TModel*, TView*>::iterator iter = std::find_if(
73  m_modelToView.begin(), m_modelToView.end(), HasId(id));
74 
75  if(iter == m_modelToView.end())
76  {
77  out_removedItem = NULL;
78  return false;
79  }
80 
81  const std::pair<TModel*, TView*>& pair = *iter;
82  TModel* pModel = pair.first;
83  Remove(*pModel);
84  out_removedItem = pModel;
85  return true;
86  }
87 
88  TViewFactory& GetViewFactory() const { return m_viewFactory; }
89  TRenderableFilter& GetRenderer() const { return m_viewRenderer; }
90 
91  protected:
92  TModelToView m_modelToView;
93 
94  private:
95  TViewFactory& m_viewFactory;
96  TRenderableFilter& m_viewRenderer;
97  };
98  }
99 }