Imports HomeSeer.PluginSdk
Public Class frmScriptImport
    Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub
    Private Sub frmScriptImport_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Me.tmrStart.Start()
    End Sub
    Private Sub tmrStart_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrStart.Tick

        Me.tmrStart.Stop()
        '' Select same File as selected in Main Form
        Me.cboFiles.SelectedIndex = theMainForm.cboFiles.SelectedIndex
        '' Put HS3 Directory to text box
        Me.txtScriptFolder.Text = My.Settings.ExportDirectory
    End Sub
    Private Sub ScriptsToList()
        Dim DI As IO.DirectoryInfo, FIs() As IO.FileInfo, FI As IO.FileInfo
        Dim s1, s2 As String
        Dim p As String
        '' Put HS3 Script Names to list
        clbScripts.Items.Clear()
        p = My.Settings.ExportDirectory
        If p.Substring(p.Length - 1) <> "\" Then p = p & "\"
        Try
            DI = New IO.DirectoryInfo(p)
            FIs = DI.GetFiles
            For Each FI In FIs
                If FI.Extension.ToUpper = ".VB" Or FI.Extension.ToUpper = ".CS" Then
                    s1 = FI.Name
                    s2 = s1.Substring(0, s1.Length - 3)
                    If Exports.ContainsKey(s2) Then
                        '' Script already imported
                        s1 = "*" & s1 & " (Already Exists in tenScripting Project)"
                        If chkShowAll.Checked Then clbScripts.Items.Add(s1)
                    Else
                        '' Script not imported yet
                        clbScripts.Items.Add(s1)
                    End If
                End If
            Next
        Catch ex As Exception
            Beep()
            theMainForm.MyLog("Exception Importing Scripts from: " & p, False, Logging.ELogType.Error)
            theMainForm.MyLog(".... " & ex.Message, False, Logging.ELogType.Error)
            MsgBox("Error Ocurred, see tenScripting log", , "tenScripting4")
            Me.Close()
        End Try
    End Sub
    Function DropAddedLines(InString As String) As String
        ''
        '' DropAddedLines is used by ScriptImport to drop any lines that were added by tenScripting during Export
        ''
        Dim Lines(), s1, s2 As String
        s1 = InString.Replace(vbCrLf, vbCr)
        Lines = s1.Split(Convert.ToChar(vbCr))
        s2 = ""
        For i1 As Integer = 0 To Lines.Count - 2
            If Lines(i1).Contains("ADDED BY tenScripting") Then
                '' Line to be excluded, do nothing
                i1 = i1
            Else
                '' Not and excluded line, so add it
                s2 = s2 & Lines(i1) & vbCrLf
            End If
        Next
        Return s2
    End Function
    Private Sub btnImportScripts_Click(sender As System.Object, e As System.EventArgs) Handles btnImportScripts.Click
        ''
        '' Import the selected Scripts from HS3
        ''
        Dim SomeChecked As Boolean = False
        Dim sr As System.IO.StreamReader, sw As System.IO.StreamWriter
        Dim s1, s2, s3, Ext, ed, p As String, scr, scr2 As String, ii As Integer
        Dim Processed As String = ""
        '' Loop through all selected Scripts
        For i As Integer = 0 To Me.clbScripts.Items.Count - 1
            If Me.clbScripts.GetItemChecked(i) Then
                '' Checked Script found
                SomeChecked = True
                '' Read this Script file
                s1 = My.Settings.ExportDirectory
                If s1.Substring(s1.Length - 1) <> "\" Then s1 = s1 & "\"
                s1 = s1 & Me.clbScripts.Items(i).ToString
                sr = New System.IO.StreamReader(s1)

                scr2 = sr.ReadToEnd()
                scr = DropAddedLines(scr2)
                sr.Close()
                '' Determine where to add the Script and append it to the Script file
                Ext = s1.Substring(s1.Length - 3).ToUpper
                Select Case Ext
                    Case ".VB"
                        s3 = cboFiles.Items(cboFiles.SelectedIndex).ToString.ToUpper
                        s3 = s3.Substring(s3.Length - 3)
                        If s3 <> ".VB" Then
                            MsgBox("You are trying to Import a VB script in to a file without an extension of .vb")
                            Exit Sub
                        End If
                        ed = My.Application.Info.DirectoryPath          'executable directory
                        ii = ed.IndexOf("bin")                           'offset to project sub directory
                        p = ed.Substring(0, ii - 14) & "VBscripts\"      'path to VBscripts project sub directory
                        p = p & cboFiles.Items(cboFiles.SelectedIndex).ToString
                        sw = New System.IO.StreamWriter(p, True)            'append
                        s2 = Me.clbScripts.Items(i).ToString
                        s2 = s2.Substring(0, s2.Length - 3)
                        sw.WriteLine(vbCrLf & "CLASS " & s2)
                        sw.Write(scr)
                        sw.WriteLine(vbCrLf & "END CLASS")
                        sw.Close()
                        Processed = Processed & Me.clbScripts.Items(i).ToString.ToUpper & vbCrLf
                    Case ".CS"
                        s3 = cboFiles.Items(cboFiles.SelectedIndex).ToString.ToUpper
                        s3 = s3.Substring(s3.Length - 3)
                        If s3 <> ".CS" Then
                            MsgBox("You are trying to Import a C# script in to a file without an extension of .cs")
                            Exit Sub
                        End If
                        ed = My.Application.Info.DirectoryPath          'executable directory
                        ii = ed.IndexOf("bin")                           'offset to project sub directory
                        p = ed.Substring(0, ii - 14) & "CSscripts\"      'path to CSscripts project sub directory
                        p = p & cboFiles.Items(cboFiles.SelectedIndex).ToString
                        sw = New System.IO.StreamWriter(p, True)            'append
                        s2 = Me.clbScripts.Items(i).ToString
                        s2 = s2.Substring(0, s2.Length - 3)
                        sw.WriteLine(vbCrLf & "public class " & s2)
                        sw.WriteLine("{")
                        sw.WriteLine("readonly HomeSeerAPI.IHSApplication hs = CSscripts.CSinit.hsobject;       // @DONOTEXPORT)")
                        sw.Write(scr)
                        sw.WriteLine("}")
                        sw.Close()
                        Processed = Processed & Me.clbScripts.Items(i).ToString.ToUpper & vbCrLf
                    Case Else
                        theMainForm.MyLog("Import found invalid extension: " & Ext, False, Logging.ELogType.Error)
                        MsgBox("Processing Error, check tenScripting Log", , "tenScripting4")
                        Exit Sub
                End Select
            End If
        Next i
        If SomeChecked Then
            '' Processed Scripts
            s2 = "The Following Scripts were Imported:" & vbCrLf & vbCrLf & Processed & vbCrLf & "   TO: " & cboFiles.Items(cboFiles.SelectedIndex).ToString & vbCrLf & vbCrLf
            s2 = s2 & "If the Imported Script contains IMPORTS or USING statements, they must be manually moved to the beginning of the Script File" & vbCrLf & vbCrLf
            s2 = s2 & "The tenScripting project will now terminate so you can edit your imported scripts"
            MsgBox(s2, , "tenScripting4")
            End
        Else
            '' None Specified
            MsgBox("No Scripts Checked", , "tenScripting4")
        End If
    End Sub
    Private Sub clbScripts_ItemCheck(sender As System.Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbScripts.ItemCheck
        Dim s As String
        s = clbScripts.Items(e.Index).ToString
        If e.NewValue = CheckState.Checked And s.Substring(0, 1) = "*" Then
            ''  The Script is already contained in the tenScripting Project
            MsgBox("Selected Script already defined in the tenScripting Project. Cannot Import it.", , "tenScripting4")
            e.NewValue = CheckState.Unchecked
        End If
    End Sub
    Private Sub chkShowAll_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkShowAll.CheckedChanged
        ''
        '' Refresh Display of Scripts
        ''
        ScriptsToList()
    End Sub
    Private Sub btnScriptFolder_Click(sender As System.Object, e As System.EventArgs) Handles btnScriptFolder.Click
        Dim frmSF As frmScriptFolder
        frmSF = New frmScriptFolder
        frmSF.ShowDialog()
        frmSF = Nothing
        '' Put HS3 Directory to text box
        Me.txtScriptFolder.Text = My.Settings.ExportDirectory
    End Sub
    Private Sub btnRetrieveScriptList_Click(sender As System.Object, e As System.EventArgs) Handles btnRetrieveScriptList.Click
        '' Put HS3 Script Names to list
        ScriptsToList()
    End Sub
End Class