117 lines
3.1 KiB
C#
117 lines
3.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using Code.Infrastructure.EventBus;
|
|
using Cysharp.Threading.Tasks;
|
|
using Newtonsoft.Json;
|
|
using UnityEngine;
|
|
|
|
namespace Code.Calendar.DataStructures
|
|
{
|
|
public interface IPlantService
|
|
{
|
|
void AddPlant(Plant plant);
|
|
void DeletePlant(Plant plant);
|
|
Plant GetPlant(Guid plantId);
|
|
List<Plant> GetPlants();
|
|
void EditPlant(Guid guid, Plant newPlant);
|
|
}
|
|
|
|
public class PlantService : IDisposable, IPlantService
|
|
{
|
|
private readonly EventBus _eventBus;
|
|
|
|
private List<Plant> _plants;
|
|
|
|
public PlantService(EventBus eventBus)
|
|
{
|
|
_eventBus = eventBus;
|
|
|
|
LoadJsonTasks().Forget();
|
|
}
|
|
|
|
private async UniTaskVoid LoadJsonTasks()
|
|
{
|
|
var path = Path.Combine(Application.persistentDataPath, "Plants.json");
|
|
|
|
if (File.Exists(path))
|
|
{
|
|
using StreamReader reader = new(path);
|
|
|
|
_plants = JsonConvert.DeserializeObject<List<Plant>>(await reader.ReadToEndAsync()) ?? new List<Plant>();
|
|
}
|
|
else
|
|
{
|
|
await using (File.Create(path)) { }
|
|
}
|
|
|
|
_eventBus.RaiseEvent<IPlantsServiceInitHandle>(x=> x.PlantsLoaded());
|
|
}
|
|
|
|
private bool _inAction, _reUseRequest;
|
|
|
|
private async UniTaskVoid SaveJsonTasks()
|
|
{
|
|
if (_inAction)
|
|
{
|
|
_reUseRequest = true;
|
|
return;
|
|
}
|
|
|
|
_inAction = true;
|
|
|
|
var json = JsonConvert.SerializeObject(_plants, Formatting.Indented);
|
|
|
|
await using StreamWriter writer = new(Path.Combine(Application.persistentDataPath, "Plants.json"));
|
|
|
|
await writer.WriteAsync(json).AsUniTask();
|
|
|
|
_inAction = false;
|
|
|
|
if(!_reUseRequest) _eventBus.RaiseEvent<IPlantsServiceInitHandle>(x=> x.PlantsSaved());
|
|
else SaveJsonTasks().Forget();
|
|
}
|
|
|
|
public void AddPlant(Plant plant)
|
|
{
|
|
plant.Id = Guid.NewGuid();
|
|
|
|
_plants.Add(plant);
|
|
|
|
SaveJsonTasks().Forget();
|
|
}
|
|
|
|
public void EditPlant(Guid guid, Plant newPlant)
|
|
{
|
|
_plants[_plants.FindIndex(x => x.Id == guid)] = newPlant;
|
|
|
|
SaveJsonTasks().Forget();
|
|
}
|
|
public void DeletePlant(Plant plant)
|
|
{
|
|
_plants.Remove(plant);
|
|
|
|
SaveJsonTasks().Forget();
|
|
}
|
|
|
|
public Plant GetPlant(Guid plantId) => _plants.FirstOrDefault(x => x.Id == plantId);
|
|
public List<Plant> GetPlants() => _plants;
|
|
|
|
public void Dispose()
|
|
{
|
|
SaveJsonTasks().Forget();
|
|
}
|
|
}
|
|
|
|
public interface IPlantsServiceInitHandle : IGlobalSubscriber
|
|
{
|
|
void PlantsLoaded();
|
|
void PlantsSaved();
|
|
}
|
|
public interface IPlantsServiceHandle : IGlobalSubscriber
|
|
{
|
|
void PlantAdded();
|
|
void PlantRemoved();
|
|
}
|
|
} |