/* --------------------------------------------------- */
/* Functions                                           */
/* --------------------------------------------------- */
let coview_api = new CoviewApi();


$(function() {
    var coviewApiActive = coview_api.Init (
        {
            testSTRParam : "param1",
            testNUMParam : 77,
            testBOOLParam : false,
            coview_api_srv_addr: "https://app.coview.co.kr:7443",
            coview_wrap_id : "coviewShare",
        }
    );

    // special button IN Chat ui



    $("#coviewShareMainBtn").on("click", function(e) {
        e.stopPropagation();
        if($(".coview_share_dropdown_bar").is(':visible') == true) {
            Coview_shareDropdownHide();

            if($(".coview_share_photo_select_bubble").is(':visible') == true) {
                $(".coview_share_photo_select_bubble").slideUp();
            }
        } else {
            $(".coview_share_dropdown_bar").slideDown();
        }
    });

    // ナビゲーションバー
    // 協業タイプ変更ボタン
    $("#coviewChangeTypeButton").on("click", function(e) {
        // ナビゲーションボタン
        $("#coviewChangeTypeButton").hide();
        $("#coviewAddMemberButton").hide();
        $("#coviewMemberButton").hide();
        $("#coviewShareCloseButton").show();
        // 協業タイプ選択画面表示
        $(".coview_type_area").show();
    });

    // 写真共有
    $("#photoBtn").on("click", function(e) {
        console.log("写真共有");
        // TODO
    });

    // 現場中継
    $("#liveBtn").on("click", function(e) {
        console.log("現場中継");
        // TODO
    });

    // 文書共有
    $("#documentBtn").on("click", function(e) {
        console.log("文書共有");
        // TODO
    });

    // 落書き
    $("#boadBtn").on("click", function(e) {
        console.log("落書き");
        // TODO
    });

    // 音声共有
    $("#voiceBtn").on("click", function(e) {
        console.log("音声共有");
        // TODO
    });

    // メンバー招待ボタン
    $("#coviewAddMemberButton").on("click", function(e) {
	    // ナビゲーションボタン
        $("#coviewChangeTypeButton").hide();
        $("#coviewAddMemberButton").hide();
        $("#coviewMemberButton").hide();
        $("#coviewShareCloseButton").show();
        // メンバー招待画面表示
        Coview_setCoviewAddMember();
        $(".coview_add_member_area").show();
    });

    // メンバー表示ボタン
    $("#coviewMemberButton").on("click", function(e) {
        // ナビゲーションボタン
        $("#coviewChangeTypeButton").hide();
        $("#coviewAddMemberButton").hide();
        $("#coviewMemberButton").hide();
        $("#coviewShareCloseButton").show();
        // メンバー表示
        $(".coview_member_area").show();
    });

    // 閉じるボタン
    $("#coviewShareCloseButton").on("click", function(e) {
        Coview_setNavigationMenu();
        $(".coview_type_area").hide();
        $(".coview_add_member_area").hide();
        // 画面表示
        switch (globalUserInfo.coWorkType) {
            case "audio":
                $(".coview_member_area").show();
                break;
            default:
                $(".coview_member_area").hide();
        }
    });


    // コントロールメニュー
    // 非表示ボタン
    $("#toolHideBtn").on("click", function(e) {
        $(".tool_hide_btn").hide();
        $(".coview_tool_area").hide();
        $(".coview_on_screen_btn_area").hide();
        $(".coview_bottom_area").hide();
        $("#coviewMemberArea").css({'height':'calc(100vh - 60px)'});
        $("#coviewMemberArea").css({'bottom':'0px'});
        $("#toolAreaSwitcher").css({'bottom':'0'});
        $(".tool_show_btn").show();
    });

    // 表示ボタン
    $("#toolShowBtn").on("click", function(e) {
        $(".tool_hide_btn").show();
        $(".coview_tool_area").show();
        $(".coview_bottom_area").show();
        $("#coviewMemberArea").css({'height':'calc(100vh - 178px)'});
        $("#coviewMemberArea").css({'bottom':'120px'});
        $("#toolAreaSwitcher").css({'bottom':'198px'});
        $(".tool_show_btn").hide();
    });

    // ペン
    $("#penBtn").on("click", function(e) {
        var flg = $(this).hasClass("active");
        if (flg == true) {
            $(this).removeClass("active");
            document.getElementById('penBtn').innerHTML = '<img class="" src="./icon/ic_collaboration_tool_pen.png" alt="">';
            FreeDrawOnOff("on");
        } else {
            $(this).addClass("active");
            document.getElementById('penBtn').innerHTML = '<img class="" src="./icon/ic_collaboration_tool_pen.png" alt="">';
            FreeDrawOnOff("off");
        }
    });

    // ポインター
    $("#pointerBtn").on("click", function(e) {
        var flg = $(this).hasClass("active");
        if (flg == true) {
            $(this).removeClass("active");
            document.getElementById('pointerBtn').innerHTML = '<img class="" src="./icon/ic_collaboration_tool_pointer.png" alt="">';
            ColorDrawOnOff("on");
        } else {
            $(this).addClass("active");
            document.getElementById('pointerBtn').innerHTML = '<img class="" src="./icon/ic_collaboration_tool_pointer.png" alt="">';
            ColorDrawOnOff("off");
        }
    });

    // クリア
    $("#clearBtn").on("click", function(e) {
        cleardrawOnCanvas();
    });

    // ページ(戻る)
    $("#pageBackBtn").on("click", function(e) {
        // TODO
    });

    // ページ(進む)
    $("#pageForwardBtn").on("click", function(e) {
        // TODO
    });

    // マイクボタン
    $("#coviewMicBtn").on("click", function(e) {
        var flg = $(this).hasClass("active");
        if (flg == true) {
            $(this).removeClass("active");
            document.getElementById('coviewMicBtn').innerHTML = '<img class="" src="./icon/ic_collaboration_mic_off.png" alt=""> ';
            // マイクOFF
            userMute();
        } else {
            $(this).addClass("active");
            document.getElementById('coviewMicBtn').innerHTML = '<img class="" src="./icon/ic_collaboration_mic_on.png" alt=""> ';
            // マイクON
            userUnMute();
        }
    });

    // レコードボタン
    $("#coviewRecBtn").on("click", function(e) {
        var flg = $(this).hasClass("active");
        if (flg == true) {
            $(this).removeClass("active");
            document.getElementById('coviewRecBtn').innerHTML = '<img class="" src="./icon/ic_collaboration_record.png" alt="">';
            // 記録終了

        } else {
            $(this).addClass("active");
            document.getElementById('coviewRecBtn').innerHTML = '<img class="" src="https://app.coview.co.kr:7443/office_img/api/icon_api_record_stop.png" alt="">';
            // 記録開始

        }
    });

    // 退室ボタン
    $("#coviewLeaveRoomBtn").on("click", function(e) {
        coview_api.LeaveRoom();
        $(".coview_share_area").hide();
    });


    $("body").on("click", function() {
        Coview_shareDropdownHide();
    });

    $(document).on("click", ".coview_share_request", function() {
        console.log("globalUserInfo", globalUserInfo);
        if($(this).hasClass("video") == true) {
            globalUserInfo.coWorkType = "video";
            $(".coview_share_title_name").text("LIVE");
        } else {
            globalUserInfo.coWorkType = "image";
            $(".coview_share_title_name").text("IMAGE");
        }
        coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
        Coview_moveToVideoShareArea();
    });

    // $('#coviewShareRequestVideo').bind('click', function()
    //     console.log("globalUserInfo", globalUserInfo);
    //     globalUserInfo.coWorkType = "video";
    //     coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    // });

    /* --------------------------------------------------- */
    /* 協業タブ      　　　　　                               */
    /* --------------------------------------------------- */

    // 通話
    $("#coviewShareChat").on("click", function() {
        console.log("ON click coviewShareChat");
        // 協業画面へ遷移
        globalUserInfo.coWorkType = "audio";
        coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
        Coview_moveToVideoShareArea();
    });

    // 文書
    $("#coviewShareDoc").on("click", function() {
        console.log("ON click coviewShareDoc");
        alert("INTO a document share mode (only audio)");
        globalUserInfo.coWorkType = "audio";
    });

    // 画像()
    $("#coviewSharePhoto").on("click", function(e) {
        e.stopPropagation();
        console.log("ON click coviewSharePhoto");
        if($(".coview_share_photo_select_bubble").is(':visible') == true) {
            $(".coview_share_photo_select_bubble").slideUp();
        } else {
            $(".coview_share_photo_select_bubble").slideDown();
        }
    });

    // 画像(カメラ)
    $("#coviewSharePhotoCamera").on("click", function() {
        $(".coview_share_photo_select_bubble").hide();
        globalUserInfo.coWorkType = "camera";
        coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
        Coview_moveToVideoShareArea();

    });

    // 画像(ライブラリ)
    $("#coviewSharePhotoGalary").on("click", function() {
        $(".coview_share_photo_select_bubble").hide();
        globalUserInfo.coWorkType = "galary";
        coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
        Coview_moveToVideoShareArea();
    });

    // 動画
    $("#coviewShareLive").on("click", function() {
        console.log("ON click coviewShareLive");
        globalUserInfo.coWorkType = "video";
        console.log("globalUserInfo", globalUserInfo);

        // var chars = "0123456789";
        // var string_length = 6;
        // var randomstring = '';
        // for (var i=0; i<string_length; i++) {
        //     var rnum = Math.floor(Math.random() * chars.length);
        //     randomstring += chars.substring(rnum,rnum+1);
        // }
        // coview_api.CreateRoom(randomstring, globalUserInfo.coWorkType);

        coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
        Coview_moveToVideoShareArea();
    });

    // ボード
    $("#coviewShareBoad").on("click", function() {
        console.log("ON click coviewShareBoad");
        // 協業画面へ遷移
        globalUserInfo.coWorkType = "audio";
        coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
        Coview_moveToVideoShareArea();
    });


    coview_api.addEventListener ("ready", function () {
        console.log("=============> READY : ready for coview api");
        coview_api.Login(globalUserInfo.loginId);
    });

    coview_api.addEventListener ("start", function () {
        console.log("=============> START : share start");
        $("#loadingIndicator").removeClass("full_active");
    });

    coview_api.addEventListener ("destroy", function () {
        console.log("=============> START : share start");
        coview_api.LeaveRoom();
        $(".coview_share_area").hide();
        $("#loadingIndicator").removeClass("full_active");
    });

    coview_api.addEventListener ("message", async function (event, json) {
        console.log("+++ addEventListener", json);
        console.log("processMessage api = ", json.api);

        switch (json.api){
            case "LoginResponse":
            break;
            case "CreateRoomResponse":
                if(json.resultCode == 200){
                    var coviewInviteMessage = "coviewsharerequest:" + globalUserInfo.coWorkType;
                    socket.emit('createMessage', {
                      text: coviewInviteMessage
                    }, 0);
                } else {
                }
            break;

            case "joinRoomInfoResponse":
                if(json.resultCode == 200){
                } else {
                    // alert(json.resultMsg + "(" + json.resultCode + ")" );
                    alert("Not exist sharing call (" + json.resultCode + ")\nPlease using share menu.");
                    coview_api.LeaveRoom();
                    $(".coview_share_area").hide();
                    $("#loadingIndicator").removeClass("full_active");
                }
                break;

            default:
                // console.log('Unrecognized api', json);
                break;
        }
    });
});

function Coview_shareDropdownHide() {
    $(".coview_share_dropdown_bar").slideUp();
    $(".coview_share_photo_select_bubble").slideUp();
}

// 協業画面へ遷移
function Coview_moveToVideoShareArea() {
    $("#loadingIndicator").addClass("full_active");
    $(".coview_share_title_name").text(getLocalizedString("talking"));
    // 表示設定
    Coview_setShareArea();
    Coview_setNavigationMenu();
    Coview_setControlMenu();
    Coview_setCoviewTypeBtn();
    Coview_setCoviewMember();
    // 時間計測開始
    startTime = new Date().getTime();
    timerId = setTimeout(Coview_setTime, 1000);
}

// 協業画面の表示設定
function Coview_setShareArea() {
    switch (globalUserInfo.coWorkType) {
        case "audio":
            $(".coview_share_area").show();
            $(".coview_member_area").show();
            $(".coview_type_area").hide();
            $(".coview_add_member_area").hide();
            break;
        default:
            $(".coview_share_area").show();
            $(".coview_member_area").hide();
            $(".coview_type_area").hide();
            $(".coview_add_member_area").hide();
    }
}

// ナビゲーションバーの表示設定
function Coview_setNavigationMenu() {
    switch (globalUserInfo.coWorkType) {
        case "audio":
            $("#coviewChangeTypeButton").show();
            $("#coviewAddMemberButton").show();
            $("#coviewMemberButton").hide();
            $("#coviewShareCloseButton").hide();
            break;
        default:
            $("#coviewChangeTypeButton").show();
            $("#coviewAddMemberButton").show();
            $("#coviewMemberButton").show();
            $("#coviewShareCloseButton").hide();
    }
}

// コントロールメニューの表示設定
function Coview_setControlMenu() {
    switch (globalUserInfo.coWorkType) {
        case "audio":
            $('#toolAreaSwitcher').hide();
            $('#coviewToolArea').hide();
            break;
        // TODO 他の協業
        default:
            $('#toolAreaSwitcher').show();
            $('#coviewToolArea').show();
    }
}

// 協業タイプ選択画面の設定
function Coview_setCoviewTypeBtn() {
    // 初期化
    $('#coviewTypeArea').html('');

    // 様式を読み込む
    const typeTemplate = $('#coview-type-template').html();

    switch (globalUserInfo.coWorkType) {
        case "audio":
            let html = Mustache.render(typeTemplate, {
                btnId1: "photoBtn",
                imgUrl1: "./icon/ic_collaboration_record.png",
                type1: getLocalizedString("sharePhoto"),
                btnId2: "liveBtn",
                imgUrl2: "./icon/ic_collaboration_record.png",
                type2: getLocalizedString("shareLive"),
                btnId3: "documentBtn",
                imgUrl3: "./icon/ic_collaboration_record.png",
                type3: getLocalizedString("shareDocument"),
                btnId4: "boadBtn",
                imgUrl4: "./icon/ic_collaboration_record.png",
                type4: getLocalizedString("shareBoad")
            });
            let obj = $(jQuery.parseHTML(html))
            $('#coviewTypeArea').append(obj);
            break;
        // TODO　他のケース
        default:
    }
}

// 協業参加メンバー画面の設定
function Coview_setCoviewMember() {
    // 初期化
    $('#coviewMemberArea').html('');

    // メンバー取得
    var memberList = coview_api.GetMemberList();

    // 様式を読み込む
    const memberTemplate = $('#coview-member-template').html();

    memberList.forEach(function(member) {
        // ホストの場合は右上に帯を追加
        // TODO ホスト判定＆プロフィール画像取得
        var className = "member_profile_btn_host";//(member == 4 ? "member_profile_btn_host":"member_profile_btn");
        let html = Mustache.render(memberTemplate, {
            className: className,
            profileImage: ""
		});

        let obj = $(jQuery.parseHTML(html)).on('click', function() {
            // TODO ネームカード表示
        });

        $('#coviewMemberArea').append(obj);
    });
}

//協業メンバー招待画面の設定
function Coview_setCoviewAddMember() {
    // 初期化
    $('#coviewFavoriteList').html('');
    $('#coviewGroupList').html('');

    // お気に入り,グループ情報取得
    var favoriteList = [1,1,1,1,1,1];
    var groupList = [1,1,1,1,1,1,1,1,1,1,1,1];

    // 様式を読み込む
    const favoriteTemplate = $('#coview-favorite-template').html();

    favoriteList.forEach(function(group) {
        let html = Mustache.render(favoriteTemplate, {
            profileImage: "https://www.silhouette-illust.com/wp-content/uploads/2016/11/15795-300x300.jpg",
            userName: "ユーザー名"
		});

        let obj = $(jQuery.parseHTML(html)).on('click', function() {
            // TODO
            console.log("お気に入りがタップされました");
        });

        $('#coviewFavoriteList').append(obj);
    });

    // 様式を読み込む
    const groupTemplate = $('#coview-group-template').html();

    groupList.forEach(function(group) {
        let html = Mustache.render(groupTemplate, {
            profileImage: "https://www.silhouette-illust.com/wp-content/uploads/2016/11/15795-300x300.jpg",
            userName: "ユーザー名"
		});

        let obj = $(jQuery.parseHTML(html)).on('click', function() {
            // TODO
            console.log("グループがタップされました");
        });

        $('#coviewGroupList').append(obj);
    });
}

// 経過時間の計算・表示
var timerId;
var startTime;
function Coview_setTime() {
    // 経過時間計算
    nowTime = new Date().getTime();
    diff = new Date(nowTime - startTime);

    // 時間表示
    var sec = diff.getSeconds();
    var min = diff.getMinutes();
    var strSec = "" + sec;
    if ( strSec.length < 2){
        strSec = "0" + strSec;
    }
    strMin = "" + min;
    if ( strMin.length < 2){
        strMin = "0" + strMin;
    }
    var strTime = strMin + ":" + strSec;
    document.getElementById("coview_time").innerHTML = strTime;
    timerId = setTimeout(Coview_setTime, 1000);
}

