1 // Copyright (C) 2018 Kazuhiro Fujieda <fujieda@users.osdn.me>
\r
3 // Licensed under the Apache License, Version 2.0 (the "License");
\r
4 // you may not use this file except in compliance with the License.
\r
5 // You may obtain a copy of the License at
\r
7 // http://www.apache.org/licenses/LICENSE-2.0
\r
9 // Unless required by applicable law or agreed to in writing, software
\r
10 // distributed under the License is distributed on an "AS IS" BASIS,
\r
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
12 // See the License for the specific language governing permissions and
\r
13 // limitations under the License.
\r
16 using System.Collections.Generic;
\r
19 namespace KancolleSniffer.Model
\r
21 public class ShipInventory : Inventory<ShipStatus>
\r
23 public ShipInventory() : base(new ShipStatus())
\r
27 protected override ShipStatus CreateDummy(int id) => new ShipStatus();
\r
29 protected override int GetId(ShipStatus ship) => ship.Id;
\r
31 public IEnumerable<ShipStatus> AllShips => AllItems;
\r
34 public class ItemInventory : Inventory<ItemStatus>
\r
36 public ItemInventory() : base(new ItemStatus())
\r
40 protected override ItemStatus CreateDummy(int id) => new ItemStatus(id);
\r
42 protected override int GetId(ItemStatus item) => item.Id;
\r
45 public abstract class Inventory<T>
\r
47 private readonly Dictionary<int, T> _dict = new Dictionary<int, T>();
\r
48 private int _inflated;
\r
50 protected abstract T CreateDummy(int id);
\r
52 protected Inventory(T dummy)
\r
60 _dict[-1] = CreateDummy(-1);
\r
64 public virtual T this[int id]
\r
66 get => _dict.TryGetValue(id, out var item) ? item : CreateDummy(id);
\r
67 set => _dict[id] = value;
\r
70 protected abstract int GetId(T item);
\r
72 public void Add(T item)
\r
74 _dict[GetId(item)] = item;
\r
77 public void Add(IEnumerable<T> items)
\r
79 foreach (var item in items)
\r
83 public void Remove(int id)
\r
89 public void Remove(IEnumerable<int> ids)
\r
91 foreach (var id in ids)
\r
95 public void Remove(T item)
\r
97 Remove(GetId(item));
\r
100 public void Remove(IEnumerable<T> items)
\r
102 foreach (var item in items)
\r
106 public bool Contains(int id) => _dict.ContainsKey(id);
\r
108 // ReSharper disable once UnusedMember.Global
\r
109 public bool Contains(T item) => Contains(GetId(item));
\r
111 public IEnumerable<T> AllItems =>
\r
112 from kv in _dict where kv.Key != -1 select kv.Value;
\r
114 public void InflateCount(int count) => _inflated += count;
\r
116 public int Count => _dict.Count + _inflated - 1;
\r
118 public int MaxId => Math.Max(_dict.Keys.Max(), 0);
\r