using EntityFrameworkCore.Triggered;
using IP2Region.Net.Abstractions;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IRaCIS.Core.Application.Triggers
{
    public class UserLogTrigger : IBeforeSaveTrigger<UserLog>
    {
        public ISearcher _searcher;

        public ILogger<UserLogTrigger> _logger;
        public UserLogTrigger(ISearcher searcher,ILogger<UserLogTrigger> logger)
        {
            _searcher = searcher;
            _logger= logger;
        }

        //国家|区域|省份|城市|ISP   缺省的地域信息默认是0
        //0|0|0|内网IP|内网IP
        // 中国|0|湖北省|武汉市|电信
        public async Task BeforeSave(ITriggerContext<UserLog> context, CancellationToken cancellationToken)
        {
            var userLog = context.Entity;

            if (context.ChangeType == ChangeType.Added)
            {

                var ipinfo = _searcher.Search(userLog.IP);

                userLog.IPRegion = string.Join('|', ipinfo.Split('|').TakeLast(3));
                

            }
        }
    }
}
