using LJLib.Net.SPI.Server;
using LJLib.Tools.Encry;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using JLHHJSvr.Com;

namespace JLHHJSvr.Excutor
{
    internal sealed class HelloWordExcutor : ExcutorBase<HelloWordRequest, HelloWordResponse>
    {
        protected override void ExcuteInternal(HelloWordRequest request, object state, HelloWordResponse rslt)
        {
            var md5 = new MD5();

            var strmd5 = md5.GetMD5(request.FileData);

            using (var con = new SqlConnection(GlobalVar.ConnectionString))
            using (var cmd = con.CreateCommand())
            {
                con.Open();
                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        cmd.CommandText = "DELETE FROM cd_files WHERE md5 = @md5";
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddWithValue("@md5", strmd5);
                        var nrows = cmd.ExecuteNonQuery();

                        cmd.CommandText = "INSERT INTO cd_files(md5, filedata) VALUES(@md5, @filedata)";
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddWithValue("@md5", strmd5);
                        cmd.Parameters.AddWithValue("@filedata", request.FileData);
                        nrows = cmd.ExecuteNonQuery();

                        cmd.Transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        Trace.Write(ex.ToString());
                        cmd.Transaction.Rollback();
                        rslt.ErrMsg = ex.ToString();
                    }
                }
            }
            rslt.RspFile = request.FileData;
        }
    }
}
