<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NewTM.aspx.cs" Inherits="Board_One2one_NewTM" meta:resourcekey="Page" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../libs/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../libs/bootstrapValidator.min.css">
    <link rel="stylesheet" href="../../libs/fontawesome/css/all.min.css" >
    <link rel="stylesheet" href="../../libs/kendoui/2023.3.1114/styles/bootstrap-3.css" />
    <script type="text/javascript" src="../../libs/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="../../libs/bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="../../libs/bootstrapValidator.min.js"></script>
    <script src="../../libs/kendoui/2023.3.1114/mjs/kendo.editor.js" type="module"></script>
</head>
<body>
    <script type="text/javascript">
        $(document).ready(function () {
            Dialog.setMessage('<asp:Literal runat="server" Text="<%$ Resources:Dialog, Title%>" />', '<asp:Literal runat="server" Text="<%$ Resources:Dialog, OK%>" />', '<asp:Literal runat="server" Text="<%$ Resources:Dialog, Cancel%>" />');
            Dialog.setUseBrowserConfirm(<%=AppSetting.UseBrowserConfirm%>);
            InitEditor();
            InitAttachFile();
            if ("<%=WebUser.CurrentUser.UiLanguage%>" == "ko") kendo.culture("ko-KR");

            $("#form1").bootstrapValidator().on('success.form.bv', function (e) {
                // 폼 서브미션 금지하고 __doPostBack 호출
                e.preventDefault();
                // 작성된 글을 게시하시겠습니까?
                Dialog.confirm({
                    content: '<asp:Literal runat="server" Text="<%$ Resources:, Msg01%>" />',
                    ok: function () {
                        __doPostBack("SaveButton", "");
                    },
                    cancel: function () {
                        // confirm 취소 시 서브밋 버튼 활성화
                        var $form = $(e.target);
                        $form.bootstrapValidator("disableSubmitButtons", false);
                    }
                });
            });
        });
        
        /*
            파일 첨부 관련 함수
        */
        var malwareInfected = false;        // 악성 코드 감염 여부

        function InitAttachFile() {
            kendo.ui.Upload.fn._supportsDrop = function () { return false; }    // 드래그&드롭 업로드 기능 off
            $("#files").kendoUpload({
                async: {
                    saveUrl: "../../Common/UploadChunk.ashx",
                    removeUrl: "../../Common/UploadRemove.ashx",
                    chunkSize: 2 * 1024 * 1024,
                    autoUpload: true
                },
                // 업로드 시작하기 전 발생
                upload: function (request) {
                    // 파라미터 추가
                    request.data = { checkMalware: true };
                    $("#addFilesOKButton").attr("disabled", true);
                },
                // 업로드 완료 시 발생
                complete: function (e) {
                    $("#addFilesOKButton").attr("disabled", false);
                },
                // 오류 응답 시 발생: 악성 코드 검출 시 발생
                error: function (e) {
                    try {
                        const cmResult = JSON.parse(e.XMLHttpRequest.responseText);
                        if (cmResult.infected) {
                            malwareInfected = true;
                            Dialog.alert(String.format('<asp:Literal runat="server" Text="<%$ Resources:, Msg05%>" />', cmResult.malware));
                        }
                    } catch { }
                }
            });
        }

        function AddFilesEx(e) {
            e.stopPropagation();
            if (malwareInfected) {
                malwareInfected = false;
                $("#files").data("kendoUpload").clearAllFiles();
            }
            $("#addFilesModal").modal();
        }

        // 파일 업로드 후 확인 버튼 클릭 -> 첨부 파일 목록을 갱신
        function AddFilesExOK() {
            $("#addFilesModal").modal("hide");
            var upload = $("#files").data("kendoUpload"), files = upload.getFiles();
            if (malwareInfected) {
                // 감염 이력이 있을 경우 모든 첨부를 제거한다.
                upload.clearAllFiles();
                malwareInfected = false;
                return;
            }
            if (files.length > 0) {
                var fileInfoList = [];
                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    var fileInfo = {
                        Uid: file.uid,
                        Name: file.name,
                        Extension: file.extension,
                        ContentType: file.rawFile.type,
                        Size: file.size
                    };
                    fileInfoList.push(fileInfo);
                }
                $("#JsonUploadFilesHidden").val(JSON.stringify(fileInfoList));
                console.log($("#JsonUploadFilesHidden").val());
                upload.clearAllFiles();
                __doPostBack("AddAttachFileButton", "");
            }
        }

        function RemoveFile(index) {
            $("#<%=RemoveAttachFileIndex.ClientID %>").val(index);
            __doPostBack("RemoveAttachFileButton", "");
        }

        function GotoBack() {
            history.back();
        }

        function ShowMessage(msg) {
            Dialog.alert(msg);
        }

        function InitEditor() {
            // 모든 #mc_container unwrap
            var html = $("#MsgTextBox").val();
            var $content = $($.parseHTML("<div>" + html + "</div>"));
            var mcContainer = $content.find("#mc_container");
            if (mcContainer.length > 0) mcContainer.contents().unwrap();
            html = $content.html();

            $("#MsgTextBox").kendoEditor({
                tools: KendoEditorTools,
                resizable: {
                    content: true,
                    toolbar: false
                },
                stylesheets: [
                    "../../css/EditorCSS.ashx"
                ],
                paste: onEditorPaste
            });

            // textarea 값을 변경 후 kendoEditor를 생성하면 변경된 값이 적용되지 않고 원 값이 적용되는 문제가 있어 생성 후 직접 적용한다.
            $("#MsgTextBox").data("kendoEditor").value(html);
        }

        function onEditorPaste(e) {
            const dataVal = e.html;
            var imgUrls = [];
            const regex = /<img[^>]+src=["']?((http|https):\/\/[^"'>\s]+)["']?[^>]*>/ig;
            while ((match = regex.exec(dataVal)) !== null) {
                imgUrls.push(match[1]);
            }

            if (imgUrls.length > 0) {
                e.html = "";

                var newTag = dataVal;
                Base64Image_loadAllImages(imgUrls).then(images => {
                    images.forEach(img => {
                        if (img == null) return;
                        const canvas = document.createElement("canvas");
                        canvas.width = img.naturalWidth;
                        canvas.height = img.naturalHeight;
                        const ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0);
                        const base64 = canvas.toDataURL("image/png");
                        newTag = newTag.replace(img.src, base64);
                    });
                    var editor = $("#MsgTextBox").data("kendoEditor");
                    editor.paste(newTag);
                }).catch(error => {
                    console.error("Image loading failed:", error);
                });
            }
        }
    </script>

    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <CompositeScript>
                <Scripts>
                    <asp:ScriptReference Path="~/libs/tabs/common.js" />
                    <asp:ScriptReference Path="~/libs/tabs/dialog.js" />
                    <asp:ScriptReference Path="~/libs/tabs/base64image.js" />
                </Scripts>
            </CompositeScript>
        </asp:ScriptManager>

        <div class="container-fluid">
            <div class="row" id="toolBar" data-spy="affix">
                <div class="col-xs-12" style="padding-top:2px;padding-bottom:2px;">
                    <button type="submit" id="saveToolButton" class="btn btn-primary"><span class="fa-solid fa-download"></span> <asp:Localize ID="Localize1" runat="server" meta:resourcekey="L01">저장</asp:Localize></button>
                    <span>&nbsp;</span>
                    <button type="button" id="closeToolButton" class="btn btn-primary" onclick="GotoBack();"><span class="fa-solid fa-xmark"></span></button>
                </div>
            </div>
        </div>

        <div class="container-fluid" style="padding-top:40px">
            <div class="form-group">
                <label for="ToTextBox"><asp:Localize ID="Localize6" runat="server" meta:resourcekey="L06">제목</asp:Localize>:</label>
                <input type="text" runat="server" id="SubjectTextBox" name="SubjectTextBox" class="form-control" placeholder="<%$ Resources:, Msg03%>" autocomplete="off"
                    required data-bv-notempty-message="<%$ Resources:, Msg02%>" />
            </div>            
            <asp:UpdatePanel ID="attachPanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
                <ContentTemplate>
                    <div class="row" style="padding-bottom:0.5em">
                        <div class="col-xs-12" data-toggle="collapse" data-target="#attachList">
                            <strong><asp:Localize ID="Localize2" runat="server" meta:resourcekey="L02">첨부 파일</asp:Localize>:</strong> 
                            <asp:Label ID="AttachSummaryLabel" runat="server"></asp:Label>
                            <button type="button" id="addAttachButton" class="btn btn-default" onclick="AddFilesEx(event)"><span class="fa-solid fa-plus"></span></button>
                        </div>
                    </div>
                    <ul id="attachList" runat="server" class="list-group collapse">
                        <asp:Literal ID="AttachListTag" runat="server" />
                    </ul>
                </ContentTemplate>
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="AddAttachFileButton" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="RemoveAttachFileButton" EventName="Click" />
                </Triggers>
            </asp:UpdatePanel>
            <div class="form-group">
                <label for="MsgTextBox"><asp:Localize ID="Localize3" runat="server" meta:resourcekey="L03">본문</asp:Localize>:</label>
                <textarea class="form-control" style="height:380px" rows="10" id="MsgTextBox" runat="server"></textarea>
            </div>
            <div class="checkbox" id="fixedTopPanel" runat="server">
                <label><input type="checkbox" id="FixedTopCheckBox" runat="server"><asp:Localize ID="Localize5" runat="server" meta:resourcekey="L05">고정글로 게시합니다.</asp:Localize></label>
            </div>
            <div class="checkbox" id="anonymousPanel" runat="server">
                <label><input type="checkbox" id="AnonymousCheckBox" runat="server"><asp:Localize ID="Localize7" runat="server" meta:resourcekey="L07">익명으로 작성합니다.</asp:Localize></label>
            </div>
            
            <div id="SrcArticleView" runat="server" style="display:none;">
                <strong><asp:Localize ID="Localize8" runat="server" meta:resourcekey="L08">질문글</asp:Localize>:</strong> 
                <div><asp:PlaceHolder ID="MsgBodyHolder" runat="server" EnableViewState="false"></asp:PlaceHolder></div>
            </div>
            <div>&nbsp;</div> 
        </div>

        <div style="display:none">            
            <asp:LinkButton ID="SaveButton" runat="server" OnClick="SaveButton_Click" /> 
            <asp:LinkButton ID="AddAttachFileButton" runat="server" OnClick="AddAttachFileButton_Click" /> 
            <asp:LinkButton ID="RemoveAttachFileButton" runat="server" OnClick="RemoveAttachFileButton_Click" />
            <asp:HiddenField ID="RemoveAttachFileIndex" runat="server" />
        </div>

        <asp:HiddenField ID="JsonUploadFilesHidden" runat="server"></asp:HiddenField>
    </form>

    <div class="modal fade" id="addFilesModal" role="dialog" data-backdrop="static">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header" style="">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4><asp:Localize ID="Localize10" runat="server" meta:resourcekey="L10">파일 첨부</asp:Localize></h4>
                </div>
                <div class="modal-body">
                    <form role="form">
                        <div class="form-group">
                            <input type="file" name="files" id="files" />
                        </div>
                        <div class="form-group">
                            <button type="button" class="btn btn-success btn-block" id="addFilesOKButton" disabled onclick="AddFilesExOK()">
                                <asp:Localize ID="Localize11" runat="server" meta:resourcekey="L11">확인</asp:Localize></button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
