<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="Tizen Web Service Template" />

    <title>Tizen Web Service Template</title>

    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <script src="js/main.js"></script>
    <script type="module">
    import {Service} from 'wrt:service';

    var pkg_id = tizen.application.getCurrentApplication().appInfo.packageId;
    var service_id = pkg_id + ".Service";

    var my_service = new Service(service_id);

    var OnReceived = function (ui_data) {
        console.log("Received Data in Service : " + ui_data[0].value);
        alert("Received Data in Service : " + ui_data[0].value);
    };

    var local_message_port = undefined;
    var message_port_listener = undefined;

    function startService() {
        if (!local_message_port) {
            local_message_port = tizen.messageport.requestLocalMessagePort(pkg_id + ".DataChannel");
            message_port_listener = local_message_port.addMessagePortListener(OnReceived);
        }
        my_service.start().then(function() {
            console.log("Succeeded to start service");
            alert("Succeeded to start service");
        }, function(error) {
            console.log("Failed to start service: " + error);
            alert("Failed to start service: " + error);
        });
    }
    function stopService() {
        my_service.stop(service_id).then(function() {
            if (local_message_port) {
                local_message_port.removeMessagePortListener(message_port_listener);
                message_port_listener = undefined;
                local_message_port = undefined;
            }
            alert("Succeeded to stop service");
        }, function(error) {
            console.log("Failed to stop service: " + error);
            alert("Failed to stop service: " + error);
        });
    }
    document.querySelector('#start_service').addEventListener('click', startService);
    document.querySelector('#stop_service').addEventListener('click', stopService);
    </script>
</head>

<body>
    <div id="main" class="page">
        <div class="contents">
            <div><button id="start_service">Start service</button></div><br/>
            <div><button id="stop_service">Stop service</button></div>
        </div>
    </div>
</body>

</html>
