using Npgsql;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SewerStammGen.DAL.Services.PostgresqlData
{
    public class PostgresqlDataService : IDisposable
    {
        protected readonly string connString; // = "Host = localhost; Database = SewerGen; Username = SewerGen; Password = SewerGen";
        NpgsqlDataSource dataSource;
        protected NpgsqlConnection? conn = null;
        protected string tableName = "";

        public PostgresqlDataService(string connectionstring, string tableName)
        {
            this.connString = connectionstring;
            var dataSourceBuilder = new NpgsqlDataSourceBuilder(connString);
            dataSource = dataSourceBuilder.Build();

            conn = dataSource.OpenConnection();
            this.tableName = string.Format("public.{0}", tableName);

        }


        public virtual async Task<bool> Delete(int id)
        {
            string command = $"DELETE " + tableName + " WHERE \"Id\" = @1";
            await using (var cmd = new NpgsqlCommand(command, conn))
            {
                cmd.Parameters.AddWithValue("1", id);
                int res = await cmd.ExecuteNonQueryAsync();
            }
            return true;
        }

        public void Dispose()
        {
            if (conn != null && conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }
    }
}
