<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebPush.aspx.cs" Inherits="Options_WebPush" meta:resourcekey="Page" %>
<%@ Register src="../Common/TopNavbar.ascx" tagname="TopNavbar" tagprefix="tabs" %>

<!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">
    <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>
    <style>
        .folder
        {
            padding-top: 4px;
            padding-bottom: 4px;
            margin-left: 4px;
            margin-right: 4px;
        }
        .wpCheckBox label
        { 
            font-weight: normal;
            padding-left: 0.7em;
        }
    </style>
</head>
<body>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#SubscribeButton").click(function () {
                Subscribe();
                return false;
            });
            $("#UnsubscribeButton").click(function () {
                Unsubscribe();
                return false;
            });
        });

        var applyWebPush = '<%=_apply%>';
        var applicationServerPublicKey = '<%=_publicKey%>';
        var isSubscribed = false;
        var swRegistration = null;
        var endpoint = '';

        function urlB64ToUint8Array(base64String) {
            var padding = '='.repeat((4 - base64String.length % 4) % 4);
            var base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/');
            var rawData = window.atob(base64);
            var outputArray = new Uint8Array(rawData.length);

            for (var i = 0; i < rawData.length; ++i) {
                outputArray[i] = rawData.charCodeAt(i);
            }
            return outputArray;
        }

        function Subscribe() {
            $("#SubscribeButton").attr('disabled', true);
            var applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
            swRegistration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: applicationServerKey
            })
            .then(function(subscription) {
                console.log('User is subscribed.');
                endpoint = subscription.endpoint;
                SubscribeOnServer(subscription);
                isSubscribed = true;
                UpdateUI();
            })
            .catch(function(err) {
                console.log('Failed to subscribe the user: ', err);
                UpdateUI();
            });
        }

        function Unsubscribe() {
            $("#UnsubscribeButton").attr('disabled', true);
            swRegistration.pushManager.getSubscription()
                .then(function(subscription) {
                    if (subscription) {
                        endpoint = subscription.endpoint;
                        return subscription.unsubscribe();
                    }
                })
                .catch(function(error) {
                    console.log('Error unsubscribing', error);
                })
                .then(function() {
                    UnsubscribeOnServer(endpoint);
                    console.log('User is unsubscribed.');
                    isSubscribed = false;
                    UpdateUI();
                });
        }

        function SubscribeOnServer(subscription) {
            var param = { scope : swRegistration.scope, endpoint: subscription.endpoint, subscription: JSON.stringify(subscription) };
            var paramStr = JSON.stringify(param);
            $.ajax({
                    type: "POST",
                    url: "WebPush.aspx/Subscribe",
                    data: paramStr,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var optionButton = $("#OptionButton");
                        optionButton.attr("disabled", false);
                        $("#<%=EndPointField.ClientID %>").val(subscription.endpoint);
                    },
                    failure: function (response) {
                    }
                });
        }

        function UnsubscribeOnServer(endpoint) {
            var param = { scope: swRegistration.scope, endpoint: endpoint, subscription: "" };
            var paramStr = JSON.stringify(param);
            $.ajax({
                    type: "POST",
                    url: "WebPush.aspx/Unsubscribe",
                    data: paramStr,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var optionButton = $("#OptionButton");
                        optionButton.attr("disabled", true);
                    },
                    failure: function (response) {
                    }
                });
        }

        function UpdateUI() {
            var subButton = $("#SubscribeButton");
            var unsubButton = $("#UnsubscribeButton");

            if (Notification.permission === 'denied') {
                subButton.attr('disabled', true);
                unsubButton.attr('disabled', true);
                $("#WebPushLabel").text('<asp:Literal runat="server" Text="<%$ Resources:, Msg01%>" />');      // 웹 푸시 기능이 차단되었습니다.
                UnsubscribeOnServer(endpoint);
                return;
            }
            
            if (isSubscribed) {
                $("#WebPushLabel").text('<asp:Literal runat="server" Text="<%$ Resources:, Msg02%>" />');      // 알림 서비스에 가입되어 있습니다.
                subButton.attr('disabled', true);
                unsubButton.attr('disabled', false);
            } else {
                $("#WebPushLabel").text('<asp:Literal runat="server" Text="<%$ Resources:, Msg03%>" />');      // 알림 서비스에 가입되어 있지 않습니다.
                subButton.attr('disabled', false);
                unsubButton.attr('disabled', true);
            }
        }

        function InitializeUI() {
            swRegistration.pushManager.getSubscription()
                .then(function (subscription) {
                    var optionButton = $("#OptionButton");
                    isSubscribed = !(subscription === null);                    
                    if (isSubscribed) {
                        endpoint = subscription.endpoint;
                        console.log('User IS subscribed.');
                        $("#<%=EndPointField.ClientID %>").val(endpoint);
                    } else {
                        console.log('User is NOT subscribed.');
                        optionButton.attr("disabled", false);
                    }
                    UpdateUI();
                });
        }

        if (applyWebPush == 'true' && applicationServerPublicKey != '') {
            if ('serviceWorker' in navigator && 'PushManager' in window) {
                console.log('Service Worker and Push is supported');
                window.addEventListener('load', function() {
                    navigator.serviceWorker.register('../<%=_swjs%>')
                    .then(function(swReg) {
                        console.log('Service Worker is registered', swReg);
                        swRegistration = swReg;
                        InitializeUI();
                    })
                    .catch(function(error) {
                        console.error('Service Worker Error', error);
                        $("#WebPushLabel").text('<asp:Literal runat="server" Text="<%$ Resources:, Msg04%>" />');      // 웹 푸시 기능이 지원되지 않습니다.
                    });
                });
            } else {
                console.warn('Push messaging is not supported');
                window.addEventListener('load', function() {
                    $("#WebPushLabel").text('<asp:Literal runat="server" Text="<%$ Resources:, Msg04%>" />');      // 웹 푸시 기능이 지원되지 않습니다.
                });
            }
        }
    </script>

    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

        <tabs:TopNavbar ID="TopMenu1" runat="server" />

        <div class="container-fluid topNavbarRegion">
        </div>

        <div class="container-fluid" style="padding-top:10px">
            <asp:Panel ID="MsgBox" runat="server" Visible="false">
                <asp:Label ID="MsgBoxLabel" runat="server" Text="Label"></asp:Label>                
            </asp:Panel>
            <h4><asp:Localize ID="Localize1" runat="server" meta:resourcekey="L01">웹 푸시 알림</asp:Localize></h4>
            <div class="form-group">
                <div class="row">
                    <div class="col-xs-12">
                        <asp:Label ID="WebPushFuncLabel" runat="server" Text="" ></asp:Label>
                    </div>
                    <div class="col-xs-12">
                        <asp:Localize ID="Localize3" runat="server" meta:resourcekey="L03">현재 상태</asp:Localize>: <asp:Label ID="WebPushLabel" runat="server" Text=""></asp:Label>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="row">
                    <div class="col-xs-12" style="text-align:center;">
                        <asp:Button ID="SubscribeButton" runat="server" Text="알림 서비스 가입" CssClass="btn btn-default" Enabled="false" meta:resourcekey="SubscribeButton" />
                        <asp:Button ID="UnsubscribeButton" runat="server" Text="알림 서비스 탈퇴" CssClass="btn btn-default" Enabled="false" meta:resourcekey="UnsubscribeButton" />
                    </div>
                </div>
                <div class="row">
					&nbsp;
				</div>
            </div>

            <h4><asp:Localize ID="Localize4" runat="server" meta:resourcekey="L04">알림 설정</asp:Localize></h4>
            <div class="form-group">
                <div class="row">
                    <div class="col-xs-12">
                        <div><asp:Localize ID="Localize5" runat="server" meta:resourcekey="L05">알림 서비스에 가입되어 있을 경우 알림 옵션을 설정할 수 있습니다.</asp:Localize></div>
                        <div><asp:Localize ID="Localize6" runat="server" meta:resourcekey="L06">알림 서비스에 가입되어 있을 경우 알림 옵션을 설정할 수 있습니다.</asp:Localize></div>
                    </div>
                </div>
                <div class="row">
					&nbsp;
				</div>
                <div class="row">
                    <div class="col-xs-12" style="text-align:center;">
                        <asp:Button ID="OptionButton" runat="server" Text="알림 옵션 설정" CssClass="btn btn-default"
                            PostBackUrl="~/Options/WebPushOption.aspx" meta:resourcekey="OptionButton" />
                        <asp:HiddenField ID="EndPointField" runat="server" /> 
                    </div>
                </div>
            </div>            
            <div class="row">&nbsp;</div>
        </div>
    </form>
</body>
</html>
