Imports System.Net
Imports System.IO

Partial Class includes_submission_settings_inc
    Inherits System.Web.UI.UserControl
    'Private _userPI As UserPI
    Private _webWS As New WebWS
    Private _commonFunctions As CommonFunctions = New CommonFunctions()
    Private _user As MembershipUser
    Private _userProfile As ProfileCommon
    Private partnerWS As PartnetWS.Service = New PartnetWS.Service
    Private webAdapter As com.racadtech.services.GoPrint2Client = New com.racadtech.services.GoPrint2Client()

    Private _originator As String
    Public Property Originator() As String
        Get
            Return _originator
        End Get
        Set(ByVal value As String)
            _originator = value
        End Set
    End Property

    Public ReadOnly Property MasterKey() As String
        Get
            Return "877k31hg333-d03423332wq-312dkazlfs-433398j543"
        End Get
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Me.Page.DataBind()

        '_userPI = New UserPI(Profile.StoreId)

        If Me.Originator = "Admin" Or Me.Originator = "HeadOffice" Or Session("EditUserFromManagement") Then
            Dim _guid As Guid = New Guid(Request.QueryString("uid"))
            _user = Membership.GetUser(_guid)
        Else
            _user = Membership.GetUser()
        End If

        _userProfile = Profile.GetProfile(_user.UserName)
        Dim _storeId As Integer = _userProfile.StoreId
        'Hide FTPSettings div if user has Module with Temp or Permanent FTP
        Dim modules As String() = webAdapter.GetStorePackages(_webWS.GetActivationIdByStoreId(_storeId), MasterKey).ModulesId.Split(",".ToCharArray())
        Dim i As Integer = 0
        For i = 0 To modules.Length - 1
            If Integer.Parse(modules(i)) = 6 Or Integer.Parse(modules(i)) = 7 Then
                Me.FTPSettingsPanel.Visible = False
                Exit For
            End If
        Next


        If Not Page.IsPostBack Then
            Dim _dataSet As New System.Data.DataSet
            _dataSet = _webWS.GetEmailSettingsByStoreId(_storeId)
            If _dataSet.Tables(0).Rows.Count > 0 Then
                Dim _email As String = _dataSet.Tables(0).Rows(0).Item("Email")
                Dim _attachmentSize As String = _dataSet.Tables(0).Rows(0).Item("AttachmentSize").ToString()
                EmailTextBox.Text = _email
                ' make additional update for those records where Attachment Size wasn't defined
                If _attachmentSize = "" Then
                    _webWS.UpdateEmailSettingsByStoreId(_storeId, _email, 5)
                End If
                AttachmentTextBox.Text = _dataSet.Tables(0).Rows(0).Item("AttachmentSize").ToString()
            Else
                _webWS.InsertEmailSettings(_storeId, _user.Email, 5)
                EmailTextBox.Text = _user.Email
                AttachmentTextBox.Text = 5
            End If
            _dataSet = _webWS.GetFtpSettingsByStoreId(_storeId)
            If _dataSet.Tables(0).Rows.Count > 0 Then
                HostNameTextBox.Text = _dataSet.Tables(0).Rows(0).Item("HostName")
                PortTextBox.Text = _dataSet.Tables(0).Rows(0).Item("Port")
                UserNameSetTextBox.Text = _dataSet.Tables(0).Rows(0).Item("UserName")
                PasswordSetTextBox.Attributes.Add("value", _dataSet.Tables(0).Rows(0).Item("Password"))
                'PasswordSetTextBox.Text = _dataSet.Tables(0).Rows(0).Item("Password")
                PathTextBox.Text = _dataSet.Tables(0).Rows(0).Item("Path")
                IsPASVCheckBox.Checked = _dataSet.Tables(0).Rows(0).Item("IsPASV")
            Else
            End If
        End If

        If Me.Originator = "Admin" Or Me.Originator = "HeadOffice" Then
            'BreakTR.Visible = True
        End If

    End Sub

    Protected Sub UpdateImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles UpdateImageButton.Click
        'If Session("EditUserFromAdmin") = True Or Session("EditUserFromManagement") Then
        '    Dim _guid = New Guid(Request.QueryString("uid"))
        '    _user = Membership.GetUser(_guid)
        'Else
        '    _user = Membership.GetUser()
        'End If
        ' 

        Dim _isEditAllowed As Boolean = True

        If Not Session("PartnerId") Is Nothing Then
            Try
                Dim _userIdForEdit As String = _user.ProviderUserKey.ToString
                Dim _affUserId As String = Session("PartnerId")
                _isEditAllowed = partnerWS.isEditAllowed(Session("PartnerId"), _user.ProviderUserKey.ToString)
            Catch ex As Exception
                _isEditAllowed = False
            End Try
        End If

        Dim _resultMessage As String = ""

        If _isEditAllowed Then

            _userProfile = Profile.GetProfile(_user.UserName)
            Dim _storeId As Integer = _userProfile.StoreId

            If Page.IsValid = True Then
                Try
                    If _webWS.GetEmailSettingsByStoreId(_storeId).Tables(0).Rows.Count > 0 Then
                        _webWS.UpdateEmailSettingsByStoreId(_storeId, EmailTextBox.Text, AttachmentTextBox.Text)
                    Else
                        _webWS.InsertEmailSettings(_storeId, EmailTextBox.Text, AttachmentTextBox.Text)
                    End If
                    If _webWS.GetFtpSettingsByStoreId(_storeId).Tables(0).Rows.Count > 0 Then
                        _webWS.UpdateFtpSettingsByStoreId(_storeId, HostNameTextBox.Text, PortTextBox.Text, UserNameSetTextBox.Text, _
                                    PasswordSetTextBox.Text, PathTextBox.Text, IsPASVCheckBox.Checked)
                    Else
                        _webWS.InsertFtpSettings(_storeId, HostNameTextBox.Text, PortTextBox.Text, UserNameSetTextBox.Text, _
                                    PasswordSetTextBox.Text, PathTextBox.Text, IsPASVCheckBox.Checked)
                    End If
                    '_resultMessage = "Submission Settings have been updated successfully"
                    _resultMessage = Me.GetLocalResourceObject("SuccessMessage")
                Catch ex As Exception
                    '_resultMessage = "Unable to update Submission Settings due to the following reason: <br/>" & ex.Message.ToString()
                    _resultMessage = Me.GetLocalResourceObject("FailureMessage") & " : <br/>" & ex.Message.ToString()
                End Try

                If Me.Originator = "Admin" Or Me.Originator = "HeadOffice" Then
                    ResultDiv.Visible = True
                    ResultLabel.Text = _resultMessage
                Else
                    CompleteFormDiv.Visible = False
                    ResultDiv.Visible = True
                    ResultLabel.Text = _resultMessage
                    Try
                        Dim _headTag As New HtmlGenericControl
                        _headTag = CType(Me.Page.Master.FindControl("MasterHeadTag"), HtmlGenericControl)
                        Dim _metaRefreshTag As LiteralControl = New LiteralControl(_commonFunctions.MetaTag("submission_settings.aspx"))
                        _headTag.Controls.Add(_metaRefreshTag)
                    Catch ex As Exception
                    End Try
                End If

            End If

        Else

            _resultMessage = "You are not allowed to edit User Submission Settings"
            CompleteFormDiv.Visible = False
            ResultDiv.Visible = True
            ResultLabel.Text = _resultMessage
        End If


    End Sub

    Protected Sub CancelImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles CancelImageButton.Click
        If Me.Originator = "Admin" Or Me.Originator = "HeadOffice" Then
            Dim _guid As Guid = New Guid(Request.QueryString("uid"))
            _user = Membership.GetUser(_guid)
        Else
            _user = Membership.GetUser()
        End If

        _userProfile = Profile.GetProfile(_user.UserName)
        Dim _dataSet As New System.Data.DataSet
        _dataSet = _webWS.GetEmailSettingsByStoreId(_userProfile.StoreId)
        If _dataSet.Tables(0).Rows.Count > 0 Then
            EmailTextBox.Text = _dataSet.Tables(0).Rows(0).Item("Email")
        Else
        End If
        _dataSet = _webWS.GetFtpSettingsByStoreId(_userProfile.StoreId)
        If _dataSet.Tables(0).Rows.Count > 0 Then
            HostNameTextBox.Text = _dataSet.Tables(0).Rows(0).Item("HostName")
            PortTextBox.Text = _dataSet.Tables(0).Rows(0).Item("Port")
            UserNameSetTextBox.Text = _dataSet.Tables(0).Rows(0).Item("UserName")
            PasswordSetTextBox.Attributes.Add("value", _dataSet.Tables(0).Rows(0).Item("Password"))
            ' PasswordSetTextBox.Text = _dataSet.Tables(0).Rows(0).Item("Password")
            PathTextBox.Text = _dataSet.Tables(0).Rows(0).Item("Path")
            IsPASVCheckBox.Checked = _dataSet.Tables(0).Rows(0).Item("IsPASV")
        Else
        End If
    End Sub


    'Protected Sub TestEmailButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles TestEmailButton.Click
    '    If Page.IsValid = True Then
    '        Try
    '            _commonFunctions.SendEmail("noreply@printitat.net", EmailTextBox.Text, "test", "test")
    '            RadAjaxManager1.ResponseScripts.Add(String.Format("alert('Testing of Email Settings has been successfully done!');"))
    '        Catch ex As Exception
    '            RadAjaxManager1.ResponseScripts.Add(String.Format("alert('" & ex.Message & "');"))
    '        End Try
    '    Else
    '    End If
    'End Sub


    Protected Sub TestFTPButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles TestFTPButton.Click
        If Page.IsValid = True Then
            Try
                TestFTP()
                RadAjaxManager1.ResponseScripts.Add(String.Format("alert('Testing of FTP Settings has been successfully done!');"))
            Catch ex As Exception
                RadAjaxManager1.ResponseScripts.Add(String.Format("alert('" & ex.Message & "');"))
            End Try
        End If
    End Sub

    Public Function TestFTP() As Boolean
        Try
            ' Declare all properties.
            Dim host As String = HostNameTextBox.Text
            Dim port As String = PortTextBox.Text
            Dim path As String = PathTextBox.Text
            Dim username As String = UserNameSetTextBox.Text
            Dim password As String = PasswordSetTextBox.Text
            Dim remoteFile As String = "sample.txt"
            Dim ftp As FTPclient

            Dim localFile As String = Server.MapPath("/") & "\sample.txt" ' "C:\sample.txt"  'Local Only!

            If (Not System.IO.File.Exists(localFile)) Then
                Try
                    Dim _streamWriter As System.IO.StreamWriter
                    _streamWriter = System.IO.File.CreateText(localFile)
                    _streamWriter.WriteLine("test")
                    _streamWriter.Close()
                Catch ex As Exception
                    Throw New Exception("[100] " & localFile & " Local System Error, Please Contact Support!")
                End Try
            End If

            ' Create new FTPClient object. ( Connection. )
            Try
                ftp = New FTPclient(host & ":" & port, username, password)
            Catch ex As Exception
                Throw New Exception("[101] " & ex.Message)
            End Try

            ' Attempt to upload test file.
            Try
                If (Not ftp.Upload(localFile, path & "/" & remoteFile)) Then
                    Throw New Exception("[104] Unable to connect and upload test document.")
                End If
            Catch ex As Exception
                Throw New Exception("[102] " & ex.Message)
            End Try

            ' Attempt to delete test file.
            Try
                If (Not ftp.FtpDelete(path & "/" & remoteFile)) Then
                    Throw New Exception("[105] Unable to connect and upload test document.")
                End If
            Catch ex As Exception
                Throw New Exception("[103] " & ex.Message)
            End Try
        Catch ex As Exception
            Throw New Exception("[150] " & ex.Message)
        End Try
        Return True
    End Function

    Protected Sub RadAjaxManager1_AjaxRequest(ByVal sender As Object, ByVal e As Telerik.WebControls.AjaxRequestEventArgs) Handles RadAjaxManager1.AjaxRequest
    End Sub
End Class
