using Dapper;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace Bp.Sync.Dto.DapperTypes
{
    public class IdsParam : SqlMapper.IDynamicParameters
    {
        private readonly List<long> _ids;
        public IdsParam(List<long> ids)
        {
            _ids = ids;
        }

        public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
        {
            var sqlCommand = (SqlCommand)command;

            sqlCommand.CommandType = CommandType.StoredProcedure;

            var idList = new List<Microsoft.SqlServer.Server.SqlDataRecord>();
            Microsoft.SqlServer.Server.SqlMetaData[] tvpDefinition =
            {
                new Microsoft.SqlServer.Server.SqlMetaData("Id", SqlDbType.BigInt)
            };
            foreach (var orderId in _ids)
            {
                var rec = new Microsoft.SqlServer.Server.SqlDataRecord(tvpDefinition);
                rec.SetInt64(0, orderId);
                idList.Add(rec);
            }

            var p = sqlCommand.Parameters.Add("@Ids", SqlDbType.Structured);
            p.Direction = ParameterDirection.Input;
            p.TypeName = "LongIdList";
            p.Value = idList;
        }
    }
}
