Imports System.Net
Imports System.IO
Imports System.Drawing

Partial Class user_Write
    Inherits System.Web.UI.Page
    '初期設定用変数の初まり
    Protected xApprove As String = "管理者認証"
    Protected xTitle As String = "小説フォーマット"
    Protected xTab As String = "小説フォーマット"
    Protected xListTitle As String = "タイトルのリスト"
    Protected xPageTitle As String = "ページのタイトル"
    '初期設定用変数の終わり


    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        'プログラムの始まり
        If Not IsPostBack Then
            'PC or Mobile
            If Request.Browser.IsMobileDevice Then
                Response.Redirect("../NotAllowed.aspx?msg=スマホではなく、PCに限定されます")
                Response.End()
            Else

            End If


            Dim xFormat As Data.DataView = SqlDataSourceFormat.Select(DataSourceSelectArguments.Empty)
            If xFormat IsNot Nothing AndAlso xFormat.Count <> 0 Then
                For i = 0 To xFormat.Count - 1
                    Select Case xFormat.Item(i).Row(1).ToString
                        Case "User"
                            xApprove = xFormat.Item(i).Row(2).ToString
                        Case "タイトル"
                            xTitle = xFormat.Item(i).Row(2).ToString
                        Case "タブ"
                            xTab = xFormat.Item(i).Row(2).ToString
                        Case "並び"
                            LabelOrder.Text = xFormat.Item(i).Row(2).ToString
                        Case "リストのタイトル"
                            xListTitle = xFormat.Item(i).Row(2).ToString
                        Case "ページのタイトル"
                            xPageTitle = xFormat.Item(i).Row(2).ToString
                    End Select
                Next
            End If

            '認証
            Dim xCode As String() = IsStatus.Split(",") 'No,date,name,mail,IP,Status,cookie(No,name,date),sw(Level)
            LabelName.Text = xCode(2)
            LabelMail.Text = xCode(3)
            Dim n As Integer = Integer.Parse(xCode(xCode.Length - 1))
            If n >= 1 Then 'Integer.Parse(xApprove) Then '
            Else
                Response.Redirect("../NotAllowed.aspx?msg=認証されていません DBに無し")
                Response.End()
            End If

            '

            TextBoxLevel.Text = "0"
            LabelID.Text = "New"
            TextBoxDate.Text = Mid(Date.Now.ToString, 1, 10)
            makeList()
            TextBoxBody.Visible = True


        End If
    End Sub

    Protected Function IsStatus() As String
        '管理者確認の問合せ
        Dim xCookie As String = ""
        If Request.Cookies("Local") IsNot Nothing Then
            xCookie = Request.Cookies("Local").Value
            Dim xTime As String = Format(Now, "hhmmss").ToString
            Dim x As String() = xCookie.Split(",")
            Dim enc As Encoding = Encoding.GetEncoding("UTF-8")
            Dim wc As WebClient = New WebClient()
            Dim host As String = System.Net.Dns.GetHostName
            Dim xPath As String = "http://" & host
            Dim st As Stream = wc.OpenRead(xPath & "/Approve/IsStatus.aspx?code=" & xTime & "," & xCookie)
            Dim sr As StreamReader = New StreamReader(st, enc)
            Dim html As String = sr.ReadToEnd()
            sr.Close()
            st.Close()
            Return html
        Else
            Return "不明,0,0,0,0,0,0,0,0,0,0"
        End If
    End Function

    Protected Sub makeList()
        'リストボックスのデータ作成
        Session("proxy") = LabelCookie.Text
        Dim dt As Data.DataView = SqlDataSourceNovelByProxy.Select(DataSourceSelectArguments.Empty)
        If dt IsNot Nothing And dt.Count <> 0 Then
            ListBoxList.Items.Clear()
            For i = 0 To dt.Count - 1
                ListBoxList.Items.Add(dt.Item(i).Row("id").ToString & vbTab & Regex.Replace(HttpUtility.HtmlDecode(dt.Item(i).Row("subject").ToString), "<[^>]*>", ""))
            Next
        End If
    End Sub

    Protected Function levelChar(ByVal x As String) As String
        'リストの繰り下げ表示
        levelChar = ""
        Dim n As Integer = Integer.Parse(x)
        Dim y As String = ""
        Select Case n
            Case 0
                levelChar = ""
            Case 1
                levelChar = "　：… "
            Case Else
                y = "　：… "
                For i = 0 To n - 1
                    y = "　" & y
                Next
                levelChar = y
        End Select
    End Function

    Protected Sub ButtonDown_Click(sender As Object, e As System.EventArgs) Handles ButtonDown.Click
        If IsPostBack Then
            Dim n As Integer = Integer.Parse(TextBoxLevel.Text) - 1
            If n < 0 Then n = 0
            TextBoxLevel.Text = n.ToString
        End If
    End Sub

    Protected Sub ButtonUp_Click(sender As Object, e As System.EventArgs) Handles ButtonUp.Click
        If IsPostBack Then
            Dim n As Integer = Integer.Parse(TextBoxLevel.Text) + 1
            TextBoxLevel.Text = n.ToString
        End If
    End Sub

    Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
        '新規ボタン
        If IsPostBack Then
            TextBoxLevel.Text = "0"
            LabelID.Text = "New"
            TextBoxDate.Text = Mid(Date.Now.ToString, 1, 10)
            TextBoxSubject.Text = ""
            'LiteralSubject.Text = ""
            TextBoxBody.Text = ""
            LabelMsg.Text = ""
            LabelMyid.Text = ""
            makeList()
            TextBoxBody.Text = ""
        End If
    End Sub

    Protected Sub Button5_Click(sender As Object, e As System.EventArgs) Handles Button5.Click
        'Delボタン
        If IsPostBack Then
            If LabelID.Text = "New" Then
                LabelMsg.Text = ""
                Exit Sub
            End If
            Session("id") = LabelID.Text
            SqlDataSourceAll.Delete()
            TextBoxLevel.Text = "0"
            LabelID.Text = "New"
            TextBoxDate.Text = Mid(Date.Now.ToString, 1, 10)
            TextBoxSubject.Text = ""
            'LiteralSubject.Text = ""
            TextBoxBody.Text = ""
            LabelMsg.Text = ""
            LabelMyid.Text = ""
            makeList()
        End If
    End Sub

    Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        '記事の書込み
        If IsPostBack Then
            If Len(TextBoxBody.Text) = 0 Then LabelMsg.Text = "本文が有りません" : Exit Sub
            If Len(TextBoxSubject.Text) = 0 Then LabelMsg.Text = "サブジェクト有りません" : Exit Sub
            If Len(TextBoxDate.Text) = 0 Then LabelMsg.Text = "日付が有りません" : Exit Sub
            Try
                Dim xDate As Date
                xDate = Date.Parse(TextBoxDate.Text)
                TextBoxDate.Text = Mid(xDate.ToString, 1, 10)
            Catch ex As Exception
                LabelMsg.Text = "日付フォーマットが違います" : Exit Sub
            End Try
            'img処理
            TextBoxBody.Text = Replace(TextBoxBody.Text, "<img src=", "<img width='100%' src=")

            Session("date") = TextBoxDate.Text
            Session("subject") = HttpUtility.HtmlEncode(TextBoxSubject.Text)
            If Len(TextBoxBody.Text) = 0 Then TextBoxBody.Text = " "
            Session("body") = HttpUtility.HtmlEncode(TextBoxBody.Text)
            Session("level") = Integer.Parse(TextBoxLevel.Text)
            Session("button") = 1 '表示
            Session("new") = "False"
            Session("menu") = ""
            Session("backcolor") = "True"
            Session("proxy") = LabelCookie.Text
            If LabelID.Text = "New" Then '新規挿入
                Session("myid") = Format(Now, "yyyyMMddhhmmss").ToString
                SqlDataSourceAll.Insert()
            Else '修正
                Session("id") = LabelID.Text
                Session("myid") = LabelMyid.Text
                SqlDataSourceAll.Update()
            End If
            makeList()
            LabelMsg.Text = "書込みが完了しました"
        End If
    End Sub

    Protected Sub ListBoxList_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ListBoxList.SelectedIndexChanged
        If IsPostBack Then
            Dim x As String() = ListBoxList.SelectedItem.ToString.Split(vbTab)
            Session("id") = x(0)
            Dim dt As Data.DataView = SqlDataSourceNovelByID.Select(DataSourceSelectArguments.Empty)
            If dt IsNot Nothing AndAlso dt.Count <> 0 Then
                LabelID.Text = dt.Item(0).Row("id").ToString
                TextBoxDate.Text = dt.Item(0).Row("date").ToString
                TextBoxSubject.Text = HttpUtility.HtmlDecode(dt.Item(0).Row("subject").ToString)
                TextBoxBody.Text = HttpUtility.HtmlDecode(dt.Item(0).Row("body").ToString)
                TextBoxLevel.Text = dt.Item(0).Row("level").ToString
                LabelButton.Text = dt.Item(0).Row("button").ToString
                LabelNew.Text = dt.Item(0).Row("new").ToString
                LabelMenu.Text = dt.Item(0).Row("menu").ToString
                LabelBackcolor.Text = dt.Item(0).Row("backcolor").ToString
                LabelMyid.Text = dt.Item(0).Row("myid").ToString
                LabelCookie.Text = dt.Item(0).Row("proxy").ToString
            End If
        End If
    End Sub

    Protected Sub HtmlEditorExtender1_ImageUploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles HtmlEditorExtender1.ImageUploadComplete
        If Not IsPostBack Then
            Dim xName As String = e.FileName & ""
            Dim xFile As String = Format(Now, "yyyyMMddhhmmss").ToString & "_" 'Replace(Replace(Replace(xDate, "/", ""), ":", ""), " ", "") & "_"
            HtmlEditorExtender1.AjaxFileUpload.SaveAs(Server.MapPath("../files/" & xFile & xName))

            Dim orig As Image = Image.FromFile(Server.MapPath("../files/" & xFile & xName))
            Dim thumbnail1 As Image = orig
            If orig.Width > 620 Then
                thumbnail1 = CreateThumbnail2(orig, 620, orig.Height / orig.Width * 620)
            End If
            'thumbnail1 = CreateThumbnail2(orig, 620, orig.Height / orig.Width * 620)
            thumbnail1.Save(Server.MapPath("../files/" & xFile & "s_" & xName), System.Drawing.Imaging.ImageFormat.Jpeg)

            e.PostedUrl = Page.ResolveUrl("../files/" & xFile & "s_" & xName)
            HtmlEditorExtender1.AjaxFileUpload.DataBind()
        End If
    End Sub

    ' DrawImageメソッドの利用（高品質）
    Protected Function CreateThumbnail2(ByVal orig As Image, ByVal w As Integer, ByVal h As Integer) As Image
        Dim thumbnail As Bitmap = New Bitmap(w, h)
        Using g As Graphics = Graphics.FromImage(thumbnail)
            g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
            g.DrawImage(orig, 0, 0, w, h)
        End Using
        Return thumbnail
    End Function

End Class
