2020-11-06 19:23:20 +01:00
using System ;
using System.Collections.Generic ;
using System.Text ;
using System.Threading.Tasks ;
using Microsoft.Extensions.Logging ;
using WotBlitzStatisticsPro.DataAccess ;
2020-11-17 12:36:02 +01:00
using WotBlitzStatisticsPro.Logic.AccountInformationPipeline.OperationContext ;
2020-11-06 19:23:20 +01:00
using WotBlitzStatisticsPro.Logic.Pipeline ;
namespace WotBlitzStatisticsPro.Logic.AccountInformationPipeline.Operations
{
2020-11-17 12:36:02 +01:00
public class SaveAccountAndTanksOperation : IOperation < IOperationContext >
2020-11-06 19:23:20 +01:00
{
private readonly IWargamingAccountDataAccessor _accountDataAccessor ;
private readonly ILogger < SaveAccountAndTanksOperation > _logger ;
public SaveAccountAndTanksOperation (
IWargamingAccountDataAccessor accountDataAccessor ,
ILogger < SaveAccountAndTanksOperation > logger )
{
_accountDataAccessor = accountDataAccessor ;
_logger = logger ;
}
2020-12-27 12:39:25 +01:00
public async Task Invoke ( IOperationContext context , Func < IOperationContext , Task >? next )
2020-11-06 19:23:20 +01:00
{
2020-11-17 12:36:02 +01:00
var contextData = context . Get < AccountInformationPipelineContextData >();
2021-02-26 16:56:39 +01:00
if (! contextData . NeedToSaveData )
{
_logger . LogInformation ( $"Proceeding without saving. Db LastBattleTime: {contextData.DbAccountInfo?.LastBattleTime}, WG LastBattleTime: {contextData.AccountInfo?.LastBattleTime}" );
if ( next != null ) await next . Invoke ( context );
return ;
}
2020-12-27 12:39:25 +01:00
if ( contextData ?. AccountInfo == null ||
contextData ?. AccountInfoHistory == null ||
contextData ?. Tanks == null ||
contextData ?. TanksHistory == null )
{
return ;
}
2020-11-17 12:36:02 +01:00
await _accountDataAccessor . AddOurUpdateAccountInfo ( contextData . AccountInfo );
await _accountDataAccessor . AddAccountInfoHistory ( contextData . AccountInfoHistory );
2020-11-06 19:23:20 +01:00
var tanksCount = 0 ;
var tankIdsAsString = new StringBuilder ();
2020-11-17 12:36:02 +01:00
foreach ( var tankInfo in contextData . Tanks )
2020-11-06 19:23:20 +01:00
{
var tankFromDb = await _accountDataAccessor . ReadTankInfo ( tankInfo . AccountId , tankInfo . TankId );
if ( tankFromDb == null || tankInfo . LastBattleTime > tankFromDb . LastBattleTime )
{
await _accountDataAccessor . AddOrUpdateTankInfo ( tankInfo );
2020-11-17 12:36:02 +01:00
await _accountDataAccessor . AddTankInfoHistory ( contextData . TanksHistory [ tankInfo . TankId ]);
2020-11-06 19:23:20 +01:00
tanksCount ++;
tankIdsAsString . Append ( $" {tankInfo.TankId}; " );
}
}
2020-11-17 12:36:02 +01:00
_logger . LogInformation ( $"Updated account {contextData.AccountInfo.AccountId} and {tanksCount} tanks: {tankIdsAsString}" );
2020-11-06 19:23:20 +01:00
2020-12-27 12:39:25 +01:00
if ( next != null ) await next . Invoke ( context );
2020-11-06 19:23:20 +01:00
}
}
}