' Copyright (C) 2025  P4pillon.org
'
' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU Affero General Public License as
' published by the Free Software Foundation, either version 3 of the
' License, or (at your option) any later version.
'
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' GNU Affero General Public License for more details.
'
' You should have received a copy of the GNU Affero General Public License
' along with this program.  If not, see <https://www.gnu.org/licenses/>.
Imports System.Data.SqlClient$
Imports System.IO
Imports System.Text

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Button1.Text = "Création du script sql en cours"
        GO()
        Button1.Text = "Créer le script sql"
    End Sub



    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: cette ligne de code charge les données dans la table 'PharmaDataSet._TABLES'. Vous pouvez la déplacer ou la supprimer selon vos besoins.
        Me.TABLESTableAdapter.Fill(Me.PharmaDataSet._TABLES)

    End Sub
    Private Sub GO()
        If My.Computer.FileSystem.FileExists(Application.StartupPath & "\Officine.sql") Then
            My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\Officine.sql")
            System.Threading.Thread.Sleep(2000)
        End If
        Dim sw As New StreamWriter(Application.StartupPath & "\Officine.sql", True, System.Text.Encoding.UTF8)
        System.Threading.Thread.Sleep(2000)
        sw.Write("IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = N'Pharma')" & vbCrLf)
        sw.Write("BEGIN" & vbCrLf)
        sw.Write("CREATE DATABASE [Pharma]" & vbCrLf)
        sw.Write("END" & vbCrLf)
        sw.Write("GO" & vbCrLf)
        sw.Write("USE [Pharma]" & vbCrLf)
        sw.Write("SET ANSI_NULLS ON" & vbCrLf)
        sw.Write("GO" & vbCrLf)
        sw.Write("SET QUOTED_IDENTIFIER ON" & vbCrLf)
        sw.Write("GO" & vbCrLf)
       

        sw.Write("IF NOT EXISTS(SELECT principal_id FROM sys.server_principals WHERE name = 'Test')" & vbCrLf)
        sw.Write("BEGIN" & vbCrLf)
        sw.Write("CREATE LOGIN Test WITH PASSWORD = 'Test12345'" & vbCrLf)
        sw.Write("END" & vbCrLf)
        sw.Write("GO" & vbCrLf)
        sw.Write("IF NOT EXISTS(SELECT principal_id FROM sys.database_principals WHERE name = 'Test')" & vbCrLf)
        sw.Write("BEGIN" & vbCrLf)
        sw.Write("CREATE USER Test FOR LOGIN Test" & vbCrLf)
        sw.Write("END" & vbCrLf)
        sw.Write("GO" & vbCrLf)
        sw.Write("BEGIN" & vbCrLf)
        sw.Write("ALTER LOGIN Test WITH DEFAULT_DATABASE = Pharma" & vbCrLf)
        sw.Write("EXEC sp_addrolemember 'db_datareader', 'Test'" & vbCrLf)
        sw.Write("EXEC sp_addrolemember 'db_datawriter', 'Test'" & vbCrLf)
        sw.Write("END" & vbCrLf)
        sw.Write("GO" & vbCrLf)
        sw.Close()
        Dim tables = TABLESTableAdapter.GetData
        Dim i = 1
        For Each Tables_row As PharmaDataSet.TABLESRow In tables.Rows
            Button1.Text = "Création du script sql en cours " & i.ToString & "/" & tables.Count
            i = i + 1
            RichTextBox1.AppendText(vbCrLf & Tables_row.TABLE_NAME & vbCrLf)
            RichTextBox1.SelectionStart = RichTextBox1.Text.Length
            RichTextBox1.ScrollToCaret()
            Application.DoEvents()
            sw = New StreamWriter(Application.StartupPath & "\Officine.sql", True)
            If Tables_row.TABLE_TYPE = "BASE TABLE" Then
                Dim con As New SqlConnection(My.Settings.PharmaConnectionString)
                con.Open()
                Dim comm As New SqlCommand("Select * From [" & Tables_row.TABLE_NAME & "]", con)
                Dim reader As SqlDataReader = comm.ExecuteReader
                Dim table As New DataTable
                table.Load(reader)
                con.Close()
                sw.Write("IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='" & Tables_row.TABLE_NAME & "' AND xtype='U')" & vbCrLf)
                sw.Write("CREATE TABLE [" & Tables_row.TABLE_NAME & "](temptemptemp nvarchar(1))" & vbCrLf)
                sw.Write("GO" & vbCrLf)

                For c = 0 To table.Columns.Count - 1
                    con.Open()
                    comm = New SqlCommand("SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" & Tables_row.TABLE_NAME & "' AND COLUMN_NAME = '" & table.Columns.Item(c).ColumnName & "'", con)
                    reader = comm.ExecuteReader
                    Dim type_table As New DataTable
                    type_table.Load(reader)
                    Dim type As String = type_table(0).Item(0).ToString

                    comm = New SqlCommand("SELECT COLUMNPROPERTY( OBJECT_ID('" & Tables_row.TABLE_NAME & "'),'" & table.Columns.Item(c).ColumnName & "','Precision')AS 'precision'", con)
                    reader = comm.ExecuteReader
                    Dim precision_table As New DataTable
                    precision_table.Load(reader)
                    Dim precision As String = precision_table(0).Item(0).ToString

                    comm = New SqlCommand("SELECT COLUMNPROPERTY( OBJECT_ID('" & Tables_row.TABLE_NAME & "'),'" & table.Columns.Item(c).ColumnName & "','Scale')AS 'scale'", con)
                    reader = comm.ExecuteReader
                    Dim scale_table As New DataTable
                    scale_table.Load(reader)
                    Dim scale As String = ""
                    If scale_table(0).Item(0) IsNot DBNull.Value Then
                        scale = scale_table(0).Item(0).ToString()
                    End If
                    Dim fulltype As String = type
                    If type = "nvarchar" Or type = "decimal" Or type = "numeric" Then


                        If precision = "-1" Then
                            fulltype = fulltype & "(MAX)"
                        Else
                            fulltype = fulltype & "(" & precision
                            If scale <> "" Then
                                fulltype = fulltype & "," & scale & ")"
                            Else
                                fulltype = fulltype & ")"
                            End If
                        End If
                    End If

                    sw.Write("IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" & Tables_row.TABLE_NAME & "'" & _
                             " AND COLUMN_NAME = '" & table.Columns.Item(c).ColumnName & "')" & vbCrLf)
                    sw.Write("BEGIN" & vbCrLf)

                    sw.Write("ALTER TABLE [" & Tables_row.TABLE_NAME & "] ADD [" & table.Columns.Item(c).ColumnName & "] " & fulltype & " NULL" & vbCrLf)
                    sw.Write("END" & vbCrLf)
                    sw.Write("GO" & vbCrLf)
                    con.Close()

                Next

                sw.Write("IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" & Tables_row.TABLE_NAME & "'" & _
                                       " AND COLUMN_NAME = 'temptemptemp')" & vbCrLf)
                sw.Write("BEGIN" & vbCrLf)
                sw.Write("ALTER TABLE [" & Tables_row.TABLE_NAME & "] DROP COLUMN temptemptemp" & vbCrLf)
                sw.Write("END" & vbCrLf)
                sw.Write("GO" & vbCrLf)

            End If
            sw.Close()
        Next
        RichTextBox1.AppendText("FIN" & vbCrLf)
        RichTextBox1.SelectionStart = RichTextBox1.Text.Length
        RichTextBox1.ScrollToCaret()
    End Sub
End Class
