﻿Imports System
Imports System.Web
Imports System.Collections
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services
Imports System.ComponentModel
Imports Newtonsoft
Imports Newtonsoft.Json
Imports System.Net
Imports System.IO

<System.Web.Script.Services.ScriptService()>
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")>
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
<ToolboxItem(False)>
Public Class FILE_UPLOAD_SERVICE
    Inherits System.Web.Services.WebService

    Private DocumentFilePath As String = "~/avatar/uploads/"

    <WebMethod(EnableSession:=True)>
    Public Sub BAUSCH_UPLOAD_FILE()
        Dim dt As New DataTable
        Dim affectedRows As Integer = 0
        Dim sResponse As String = ""
        If HttpContext.Current.Request.Files.Count > 0 AndAlso Not IsNothing(HttpContext.Current.Request.Form("REP_ID")) Then
            Try
                Dim REP_ID As String = HttpContext.Current.Request.Form("REP_ID")

                Dim files As HttpFileCollection = HttpContext.Current.Request.Files
                Dim file As HttpPostedFile = files(0)
                'Dim fs As Stream = file.InputStream
                'Dim br As New BinaryReader(fs)
                'Dim filebytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))

                Dim ext As String = ""
                If file.FileName.LastIndexOf(".") > 0 Then
                    ext = file.FileName.Substring(file.FileName.LastIndexOf("."))
                End If

                Dim filename As String = Guid.NewGuid().ToString() & ext '& ".tmp"
                Dim FilePath As String = Path.Combine(Server.MapPath(functions.AvatarUploadPath), "")
                Dim FullFilePath As String = Path.Combine(FilePath, filename)
                If Not IO.Directory.Exists(FilePath) Then
                    IO.Directory.CreateDirectory(FilePath)
                End If
                file.SaveAs(FullFilePath)
                Dim filebytes As Byte() = IO.File.ReadAllBytes(FullFilePath)

                'UPDATE TABLE
                Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("BAUSCH_ConnectionString").ConnectionString)
                    Using cmd As SqlCommand = New SqlCommand("REP_IMAGE_SpUpd", con)
                        cmd.CommandType = CommandType.StoredProcedure

                        cmd.Parameters.AddWithValue("@REP_ID", REP_ID)
                        cmd.Parameters.AddWithValue("@REP_IMAGE", filebytes)

                        If con.State = ConnectionState.Closed Then con.Open()

                        Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
                            affectedRows = da.Fill(dt)
                        End Using
                    End Using
                End Using


                If affectedRows > 0 Then
                    sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(True, filename), Newtonsoft.Json.Formatting.Indented)
                Else
                    sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(False, "An error has occurred: Unable to upload file"), Newtonsoft.Json.Formatting.Indented)
                End If


            Catch ex As Exception
                sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(False, "An error has occurred: " & ex.Message), Newtonsoft.Json.Formatting.Indented)
            End Try

        ElseIf HttpContext.Current.Request.Files.Count > 0 Then
            Try

                Dim files As HttpFileCollection = HttpContext.Current.Request.Files
                Dim file As HttpPostedFile = files(0)

                Dim ext As String = ""
                If file.FileName.LastIndexOf(".") > 0 Then
                    ext = file.FileName.Substring(file.FileName.LastIndexOf("."))
                End If

                Dim filename As String = Guid.NewGuid().ToString() & ext '& ".tmp"
                Dim FilePath As String = Path.Combine(Server.MapPath(functions.AvatarUploadPath), "")
                Dim FullFilePath As String = Path.Combine(FilePath, filename)
                If Not IO.Directory.Exists(FilePath) Then
                    IO.Directory.CreateDirectory(FilePath)
                End If
                file.SaveAs(FullFilePath)

                If affectedRows = 0 Then
                    sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(True, filename), Newtonsoft.Json.Formatting.Indented)
                Else
                    sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(False, "An error has occurred: Unable to upload file"), Newtonsoft.Json.Formatting.Indented)
                End If


            Catch ex As Exception
                sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(False, "An error has occurred: " & ex.Message), Newtonsoft.Json.Formatting.Indented)
            End Try
        Else
            sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(False, "An error has occurred: No files selected"), Newtonsoft.Json.Formatting.Indented)
        End If

        HttpContext.Current.Response.Write(sResponse)
    End Sub

    Public Shared Function IsValidEmail(ByVal email As String) As Boolean
        If String.IsNullOrWhiteSpace(email) Then Return False

        'Dim regex As Regex = New Regex("^[_a-z0-9-]+(.[a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$")
        'Return regex.IsMatch(email)
        Try
            Dim mail As New Net.Mail.MailAddress(email)
            Return True
        Catch ex As Exception
            Return False
        End Try

    End Function


    <WebMethod(EnableSession:=False)>
    Public Sub UPLOAD_FILE()
        Dim dt As New DataTable
        Dim affectedRows As Integer = 0
        Dim sResponse As String = ""

        Try

            If HttpContext.Current.Request.Files.Count > 0 Then
                Dim files As HttpFileCollection = HttpContext.Current.Request.Files
                Dim file As HttpPostedFile = files(0)
                Dim ext As String = ""
                If file.FileName.LastIndexOf(".") > 0 Then
                    ext = file.FileName.Substring(file.FileName.LastIndexOf("."))
                End If

                Dim filename As String = Guid.NewGuid().ToString() & ext
                Dim FilePath As String = Server.MapPath("../productdetails/")
                Dim FullFilePath As String = Path.Combine(FilePath, filename)
                If Not IO.Directory.Exists(FilePath) Then
                    IO.Directory.CreateDirectory(FilePath)
                End If
                file.SaveAs(FullFilePath)

                sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(True, filename), Newtonsoft.Json.Formatting.Indented)

            ElseIf HttpContext.Current.Request.Files.Count > 0 Then
                'Try
                '    Dim filename As String = Guid.NewGuid().ToString() + ".jpg"
                '    Dim files As HttpFileCollection = HttpContext.Current.Request.Files
                '    For i As Integer = 0 To files.Count - 1
                '        Dim file As HttpPostedFile = files(i)
                '        Dim fname As String = Path.Combine(Server.MapPath(DocumentFilePath), filename)
                '        file.SaveAs(fname)
                '    Next
                '    sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(True, filename), Newtonsoft.Json.Formatting.Indented)
                'Catch ex As Exception
                '    sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(False, "An error has occurred: " & ex.Message), Newtonsoft.Json.Formatting.Indented)
                'End Try
            Else
                sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(False, "An error has occurred: No files selected"), Newtonsoft.Json.Formatting.Indented)
            End If

        Catch ex As Exception
            sResponse = Json.JsonConvert.SerializeObject(functions.JSON_write_boolean_response(False, "An error has occurred: " & ex.Message), Newtonsoft.Json.Formatting.Indented)
        End Try


        HttpContext.Current.Response.Write(sResponse)
    End Sub


End Class