using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using MercatorApi;
using MercatorExtensions;
using MercatorUi;
using MercatorDatabase;

// <CompileWithRoslyn />

namespace MyNameSpace
{
    public class Class1 : MercatorUi.Interfaces.IExec
    {

        public void Main()
        {
            DataSet ds = Api.Zselect(MercatorUi.Globals.RepData, @"select id,filecontent from FILES where (filepath like '<Files\ACH\%') and (filecontent is not null) and (DATALENGTH(filecontent) > 0) and (dbo.IS_BINARY_MERCATORENCRYPTED(filecontent)=0)");
            if (ds == null)
                return;
            int nok = 0;
            int nko = 0;
            using (MercatorSqlConnection conn = new MercatorSqlConnection(MercatorUi.Globals.RepData, true))
            {
                if (conn.Connection == null)
                    return;
                Api.IsWeb = true; // geen foutmelding krijgen als Api.SqlExec false teruggeeft
                try
                {
                    MercatorUi.Progress.ProgressCreate(ds.Tables[0].Rows.Count);
                    using (SqlCommand cmd = new SqlCommand("update FILES set filecontent=@filecontent where id=@id", conn.Connection))
                    {
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            MercatorUi.Progress.ProgressCreate(1);
                            cmd.Parameters.AddWithValue("@id", dr["id"]); //guid -> uniqueidentifier
                            cmd.Parameters.AddWithValue("@filecontent", MercatorCryptorEngine.CryptorEngine.MercatorEncryptRsaAes((byte[])dr["filecontent"]));
                            if (Api.SqlExec(cmd))
                                nok++;
                            else
                                nko++;
                            cmd.Parameters.Clear();
                        }
                    }
                    MercatorUi.Progress.ProgressDestroy();
                }
                finally
                {
                    Api.IsWeb = false;
                }
            }
            Dialogs.Stop($"Versleutelde bestanden: {nok}.\r\nNiet-versleutelde bestanden: {nko}.");
        }
    }
}