﻿Imports Telerik.WebControls

Partial Class order_centre_Upload
    Inherits System.Web.UI.Page
    'Inherits BasePage
    Private _webAdapter As New WebWS()
    Private _goPrint2Adapter As New com.racadtech.services.GoPrint2Client()
    Private pdfConverterWS As New com.racadtech.services.PDFConverter()

    Dim _customerId As String = ""
    Dim _activationId As String = ""
    Dim _files As String = "filename1@@@302131%%%"
    Dim _emailSent As String = ""
    Dim _ftpSent As String = ""
    Dim _jobOptions As String = ""
    Dim _uploadMethod As String = ""
    Dim _masterKey As String = MasterKey
    Dim _jobId As String = ""


    Public ReadOnly Property TempDirectory() As String
        Get
            Return ConfigurationManager.AppSettings.Get("PrintItTempDataPath").ToString()
        End Get
    End Property
    Public ReadOnly Property WebAdapter() As WebWS
        Get
            Return _webAdapter
        End Get
    End Property
    Public ReadOnly Property GoPrint2Adapter() As com.racadtech.services.GoPrint2Client
        Get
            Return _goPrint2Adapter
        End Get
    End Property
    Public ReadOnly Property JobFilesDirectory() As String
        Get
            Return ConfigurationManager.AppSettings.Get("JobFilesPath").ToString()
        End Get
    End Property
    Public ReadOnly Property JobFilesVirtualDirectory() As String
        Get
            Return ConfigurationManager.AppSettings.Get("JobFilesVirtualDirectory").ToString()
        End Get
    End Property
    Public ReadOnly Property MasterKey() As String
        Get
            Return "877k31hg333-d03423332wq-312dkazlfs-433398j543"
        End Get
    End Property
    Public ReadOnly Property CurrentUser() As String
        Get
            Return System.Web.HttpContext.Current.User.Identity.Name.ToString()
        End Get
    End Property
    Public ReadOnly Property CurrentUserId() As String
        Get
            Return Membership.GetUser(CurrentUser).ProviderUserKey.ToString()
        End Get
    End Property
    Public ReadOnly Property CurrentCustomerId() As String
        Get
            If Not Session("CustomerId") Is Nothing Then
                Return Session("CustomerId")
            Else
                Return WebAdapter.GetCustomerIdByUserId(CurrentUserId)
            End If
        End Get
    End Property
    Public ReadOnly Property CurrentActivationId() As String
        Get
            Return WebAdapter.GetActivationIdByStoreId(Session("StoreId")).ToString()
        End Get
    End Property
    Public ReadOnly Property BaseImageURL() As String
        Get
            If Not Session("BaseImageURL") Is Nothing Then
                Return Session("BaseImageURL")
            Else
                Return "themes/orange/"
            End If
        End Get
    End Property

    Public ReadOnly Property CurrentLanguage() As String
        Get
            Return System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.ToLower()
        End Get
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If (Not System.Web.HttpContext.Current.User.Identity.IsAuthenticated()) Then
            Response.Redirect("~/order_centre/getting_started.aspx")
        End If

		Dim _storeId As Integer = Session("StoreId")
        'Response.Write(_storeId)

        If Session("ThankYou") = "true" Then
            Response.Redirect("~/order_centre/job_options.aspx")
        End If


        ' Disable Language Panel.
        Dim _languagesPanel As Web.UI.WebControls.Panel = Me.Master.FindControl("LanguagesPanel")
        Dim _languagesSpacer As Web.UI.HtmlControls.HtmlGenericControl = Me.Master.FindControl("LanguagesSpacerLabel")
        _languagesPanel.Visible = False
        _languagesSpacer.InnerHtml = "<br /><br />"

        RadUpload.ControlObjectsVisibility = Telerik.WebControls.ControlObjectsVisibility.RemoveButtons Or Telerik.WebControls.ControlObjectsVisibility.AddButton

        _customerId = CurrentCustomerId
        _activationId = CurrentActivationId
        _jobOptions = Session("JobOptions")

		' Remove Convert To PDF Option for Particular Store.
		
		If (_storeId = 995) Then
			ConvertPDFPanel.Visible = False
		End If

        If (_storeId = 2066) Then
            ConvertPDFPanel.Visible = False
        End If
		
        If Not Page.IsPostBack Then
            ' Create an empty job record for obtaining Job Id
            ' 
            Try
                Dim _tempJobId As String = Session("TempJobId")
                If _tempJobId Is Nothing Then
                    _jobId = GoPrint2Adapter.InsertNewJobFiles(_customerId, _activationId, _files, _emailSent, _ftpSent, _jobOptions, _uploadMethod, _masterKey)
                    Session("TempJobId") = _jobId
                Else
                    _jobId = _tempJobId
                End If
            Catch ex As Exception
                Response.Redirect("~/order_centre/error_page.aspx")
            End Try

            ' Initialize RadUpload Settings.
            ' 
            If (Not System.IO.Directory.Exists(JobFilesDirectory & "/" & _jobId)) Then
                Try
                    System.IO.Directory.CreateDirectory(JobFilesDirectory & "/" & _jobId)
                Catch ex As Exception
                End Try
            End If
            RadUpload.TargetPhysicalFolder = JobFilesDirectory & "/" & _jobId

            ' Define Top Panel Header Text.
            'Dim topPanelHeaderLabelControl As Web.UI.WebControls.Label = Me.Master.FindControl("TopPanelHeaderLabel")
            'topPanelHeaderLabelControl.Text = "&nbsp; &nbsp; &nbsp; UPLOAD YOUR FILES:"
            ' 
            Session("ConvertToPdf") = False
        End If

    End Sub

    Protected Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles UploadButton.Click
        _emailSent = "t"
        _ftpSent = "f"
        _uploadMethod = "web"
        _files = ""

        Dim _storeId As Integer = Session("StoreId")
        'Dim _profile As ProfileCommon = Profile.GetProfile(_user.UserName)

        ' Remove RadUpload Button UI.
        UploadButton.Visible = False
        RadUpload.ControlObjectsVisibility = ControlObjectsVisibility.None

        If (RadUpload.UploadedFiles.Count > 0) Then

            Dim _fileNamesArray As ArrayList = New ArrayList()

            ' Create a string filename1@@@filesize1%%%filename2@@@filesize2%%%
            For Each file As UploadedFile In RadUpload.UploadedFiles
                ' Response.Write(file.FileName & "<br>")
                Dim _fileName As String = file.GetName
                Dim _fileSize As String = file.InputStream.Length.ToString
                _files = _files & _fileName & "@@@" & _fileSize & "%%%"
            Next

            ' Update a job record with new files data
            Try
                If Not Session("TempJobId") Is Nothing Then
                    _jobId = Session("TempJobId")
                End If
                Me.GoPrint2Adapter.UpdateNewJobFiles(_jobId, _customerId, _activationId, _files, _emailSent, _ftpSent, _uploadMethod, _masterKey)
            Catch ex As Exception
            End Try

            Dim _path As String = JobFilesDirectory & "\" & _jobId

            If _jobId <> "" Then
                'If (Not System.IO.Directory.Exists(JobFilesDirectory & "/" & _jobId)) Then
                '    Try
                '        System.IO.Directory.CreateDirectory(JobFilesDirectory & "/" & _jobId)
                '    Catch ex As Exception
                '    End Try
                'End If

                For Each file As UploadedFile In RadUpload.UploadedFiles

                    'Dim bytes(file.InputStream.Length) As Byte
                    'file.InputStream.Read(bytes, 0, file.InputStream.Length)

                    Dim _fileSize As String = file.InputStream.Length.ToString

                    'Dim _fileObject As New System.IO.FileStream(_path & "\" & file.FileName, System.IO.FileMode.Open)
                    'Dim _fileSize As String = _fileObject.Length().ToString()
                    '_fileObject.Close()
                    '_fileObject.Dispose()

                    'escape special symbols
                    Dim _arrSymbols() As String
                    _arrSymbols = New String() {"~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "'", ":", ";", ",", "<", ">", "{", "[", "]", "+", "=", " ", "’", ".", "•"}
                    Dim i As Integer

                    Dim _originalFileName As String = file.GetName
                    Dim _fileNameParts As String() = com.racadtech.Framework.Util.IO.IOFile.GetDocumentName(_originalFileName, True).Split(".")
                    Dim _fileNameWithoutExtension As String = ""
                    For i = 0 To _fileNameParts.Length - 2
                        _fileNameWithoutExtension = _fileNameWithoutExtension & _fileNameParts(i).ToString()
                        If i <> _fileNameParts.Length - 2 Then
                            _fileNameWithoutExtension = _fileNameWithoutExtension & "_"
                        End If
                    Next
                    'Dim _fileNameWithoutExtension As String = _fileNameParts(0).ToString()
                    Dim _fileNameExtension As String = _fileNameParts(_fileNameParts.Length - 1).ToString()
                    For i = 0 To _arrSymbols.Length - 1
                        If _fileNameWithoutExtension.IndexOf(_arrSymbols(i)) <> -1 Then _fileNameWithoutExtension = Replace(_fileNameWithoutExtension, _arrSymbols(i), "_")
                    Next

                    '
                    ' Check if file name is already exists
                    '

                    For k As Integer = 0 To _fileNamesArray.Count - 1
                        If _fileNamesArray(k) = _fileNameWithoutExtension Then
                            _fileNameWithoutExtension = _fileNameWithoutExtension & "_"
                        End If
                    Next
                    _fileNamesArray.Add(_fileNameWithoutExtension)


                    '
                    ' Rename document under conditions;
                    ' - PDF Converter is Checked.
                    ' - File is supported by the PDF Converter Server.
                    '
                    Dim _fileName As String = _fileNameWithoutExtension & "." & _fileNameExtension
                    If PdfConvertionCheckBox.Checked Then
                        If (pdfConverterWS.IsFileSupported(_fileName)) Then
                            _fileName = _fileNameWithoutExtension & "_" & _fileNameExtension & "." & _fileNameExtension
                        End If
                    End If

                    Dim _fileServerLocation As String = "/" & JobFilesVirtualDirectory & "/" & _jobId & "/" & _fileName

                    ' Update FileName and ServerLocation 

                    Me.GoPrint2Adapter.UpdateJobFile(_jobId, _originalFileName, _fileName, _fileSize, _fileServerLocation, _activationId, MasterKey)

                    ' rename uploaded file (for the purpose of escaping special characters)
                    If _fileName <> file.GetName Then

                        If System.IO.File.Exists(_path & "\" & _fileName) = False Then
                            Try
                                System.IO.File.Move(_path & "\" & file.GetName, _path & "\" & _fileName)
                                If System.IO.File.Exists(_path & "\" & file.GetName) = True Then
                                    System.IO.File.Delete(_path & "\" & file.GetName)
                                End If
                            Catch ex As Exception
                            End Try
                        End If
                    End If
                Next
            End If
            Session("JobId") = _jobId
            Session("TempJobId") = Nothing
            If PdfConvertionCheckBox.Checked Then
                Session("ConvertToPdf") = True
            Else
                Session("ConvertToPdf") = False
            End If
            Response.Redirect("~/order_centre/process_document.aspx")
        End If
    End Sub

End Class
