@using PantheonRA.BackOffice
@using PAW.Contracts.Enums;
@using PantheonRA.WebApi.Contracts.Enums;

@{
    bool isTimeRecordsPage = Html.IsActive("Index", "TimeRecords") ? true : false;
}

<div class="navbar">
    <div class="row top-menu-wrapper">

        @*TODO: display when favorite pages are implemented *@
        @*<ul class="nav navbar-nav top-menu pull-left">
                <li class="top-menu-item pull-right">
                    <span data-toggle="dropdown">
                        <i class="fas fa-user clickable-icon" title="@Loc.LogOut"></i>
                    </span>
                </li>
            </ul>*@

        <ul class="nav navbar-nav top-menu pull-left">
            <li>
                @Html.Partial("_HeaderLogos")
            </li>
        </ul>

        <ul class="nav navbar-nav top-menu pull-right">
            <li class="top-menu-item pull-right">
                <span data-toggle="dropdown">
                    <i class="fas fa-user clickable-icon" title="@Loc.LogOut"></i><span id="header-username" class="m-l-sm">@PantheonRA.BackOffice.CurrentUser.UserName</span>
                </span>
                <ul class="dropdown-menu dropdown-menu-right">
                    <li class="dropdown-submenu">
                        <a tabindex="-1" href="#" class="dropdown-menu-icon"><span>@Loc.ChangeTheme</span> <span class="caret caret-right m-l-sm"></span></a>
                        <ul class="dropdown-menu dropdown-menu-left">
                            <li class="dropdown-item">
                                <a href="#" onclick="changeTheme('trademark')">@Loc.TrademarkThemeName</a>
                            </li>
                            <li class="dropdown-item">
                                <a href="#" onclick="changeTheme('blue')">@Loc.BlueThemeName</a>
                            </li>
                            <li class="dropdown-item">
                                <a href="#" onclick="changeTheme('green')">@Loc.GreenThemeName</a>
                            </li>
                            <li class="dropdown-item">
                                <a href="#" onclick="changeTheme('dark')">@Loc.DarkThemeName</a>
                            </li>
                        </ul>
                    </li>

                    <li class="dropdown-submenu">
                        <a tabindex="-1" href="#" class="dropdown-menu-icon"><span>@Loc.ChangeLanguage</span> <span class="caret caret-right m-l-sm"></span></a>
                        <ul class="dropdown-menu dropdown-menu-left">
                            @foreach (Lang.Code lang in Loc.Languages())
                            {
                                var imagePath = "~/Content/Images/CountryFlags/flag-" + Lang.ToPantheonLang(lang) + ".svg";
                                <li class="dropdown-item">
                                    <a href="#" onclick="changeLanguage('@Lang.ToPantheonLang(lang)')">
                                        <img src="@Url.Content(imagePath)" /><span>@Lang.ToPantheonLang(lang)</span>
                                    </a>
                                </li>
                            }
                        </ul>
                    </li>

                    @if (isTimeRecordsPage)
                    {
                        <li class="dropdown-item"><a href="javascript:void(0)" onclick="openModal('entry-type-modal');">@Loc.TimeRecordSettings</a></li>
                    }

                    @*<li class="dropdown-item"><a href="javascript:void(0)" onclick="openChangePasswordModal();">@Loc.ChangePassword</a></li>*@
                    <li class="dropdown-submenu">
                        <a tabindex="-1" href="#" class="dropdown-menu-icon"><span>@Loc.ChangePassword</span> <span class="caret caret-right m-l-sm"></span></a>
                        <ul class="dropdown-menu dropdown-menu-left">
                            <li class="dropdown-item">
                                <a href="javascript:void(0)" onclick="openChangePasswordModal();">@Loc.ChangePassword</a>
                            </li>
                            <li class="dropdown-item">
                                <a href="javascript:void(0)" onclick="openEmailSettingsModal();">@Loc.EmailSettings</a>
                            </li>
                        </ul>
                    </li>

                    <li role="separator" class="divider"></li>

                    <li class="dropdown-item">
                        <a href="javascript:void(0)" onclick="logout();" class="dropdown-menu-icon"><span>@Loc.Loggout</span><span class="fa fa-lock"></span></a>
                    </li>

                </ul>
            </li>

            @if (CurrentUser.HasAnyPermission(
                    Permissions.DefaultPermissions
                    .Where(s => s != Permissions.EMPLOYEES &&
                    s != Permissions.EMPLOYEES_OWN_DATA &&
                    s != Permissions.EMPLOYEES_EMPLOYEES &&
                    s != Permissions.EMPLOYEES_PAYCHECK &&
                    s != Permissions.TRAVEL_ORDERS &&
                    s != Permissions.TRAVEL_ORDERS_OWN_DATA &&
                    s != Permissions.TIME_RECORDS)))
            {
                <li class="top-menu-item pull-right header-icon header-notification">
                    <span data-toggle="dropdown">
                        <div class="icon-wrapper">
                            <i class="fas fa-bell clickable-icon" title="@Loc.Announcements" aria-hidden="true"></i>
                            <span class="icon-badge"></span>
                        </div>
                    </span>
                    <div class="notification-drawer">
                        <h2>@Loc.Announcements</h2>
                        <hr />
                        <div class="notification-drawer-content">
                            <i class="fa fa-spinner fa-spin fa-2x fa-fw text-muted"></i>
                        </div>
                    </div>
                </li>
            }

            <li class="top-menu-item pull-right">
                <span data-toggle="dropdown">
                    <i class="fas fa-question clickable-icon" title="@Loc.Help"></i>
                </span>
                <ul class="dropdown-menu dropdown-menu-right">
                    <li class="dropdown-item">
                        <a id="globalHelpUrl" href="@(string.IsNullOrEmpty(ViewBag.HelpUrl) ? Loc.HelpUrl + PantheonRA.BackOffice.Enums.HelpIds.Root : ViewBag.HelpUrl)" target="_blank">@Loc.Instructions</a>
                    </li>
                    <li class="dropdown-item">
                        <a id="globalExampleHelpUrl" href="@(string.IsNullOrEmpty(ViewBag.ExampleHelpUrl) ? Loc.HelpUrl + PantheonRA.BackOffice.Enums.HelpIds.Root : ViewBag.ExampleHelpUrl)" target="_blank">@Loc.SeeExamplesInInstructions</a>
                    </li>
                    <li class="dropdown-item">
                        <a id="globalHelpVideoUrl" href="@(string.IsNullOrEmpty(ViewBag.VideoHelpUrl) ? Loc.SeeVideoInstructionsUrl : ViewBag.VideoHelpUrl)" target="_blank">@Loc.SeeVideoInstructions</a>
                    </li>
                    <li class="dropdown-item">
                        <a href="@string.Format(Loc.WhatIsNewUrl, PantheonRA.BackOffice.CurrentUser.DbBuildVersion)" target="_blank">@Loc.WhatIsNew</a>
                    </li>
                    <li class="dropdown-item">
                        <a href="@Loc.CheckOutQuestionsAndAnswersUrl" target="_blank">@Loc.CheckOutQuestionsAndAnswers</a>
                    </li>
                    <li class="dropdown-item">
                        <a href="@Loc.CommunicateQuestionToTheSupporterUrl" target="_blank">@Loc.CommunicateQuestionToTheSupporter</a>
                    </li>
                    <li class="dropdown-item">
                        <a href="@Loc.RemoteSupportUrl" target="_blank">@Loc.RemoteSupport</a>
                    </li>
                    @if (CurrentUser.IsHost)
                    {
                        <li class="dropdown-item">
                            <a href="@(Loc.CloudSupportLoginUrl + "?S=" + PantheonRA.BackOffice.CurrentUser.Enc)" target="_blank">@Loc.CloudSupportLogin</a>
                        </li>
                    }
                    <li class="dropdown-item">
                        <a href="@Loc.OrderGranulesUrl" target="_blank">@Loc.OrderAdditionalServices</a>
                    </li>
                    <li class="dropdown-item">
                        <a href="@Url.Action("Index", "Company")">@Loc.AboutPantheon</a>
                    </li>
                </ul>
            </li>

            @*TODO: Uncomment when global search implemented*@
            @*<li class="top-menu-item pull-right">
                    <span data-toggle="dropdown">
                        <i class="fas fa-search clickable-icon" title="@Loc.Search"></i>
                    </span>
                </li>*@

            <li class="top-menu-item top-menu-item-text pull-right hidden-xs">
                <span id="header-domain" title="@PantheonRA.BackOffice.CurrentUser.DomainName">
                    @PantheonRA.BackOffice.CurrentUser.DomainName
                </span>
            </li>
        </ul>
    </div>
</div>

@Html.Partial("~/Views/Account/_ChangePassword.cshtml")
@Html.Partial("~/Views/Account/_EmailSettings.cshtml")

<script>
    function logout() {
        window.localStorage.setItem('AnnouncmentDataFetched', false);
        window.location = '@Url.Action("LogOut", "Account")';
    }

    function loadNotifications() {
        $('.header-notification .fa-bell').closest("span[data-toggle='dropdown']").on('click', function () {
            $('.header-notification .notification-drawer').toggle();
        });

        if (window.localStorage.getItem('AnnouncmentDataFetched') === 'true') {
            generateAnnouncementItems(JSON.parse(window.localStorage.getItem('AnnouncementsData')));
        }
        else {
            $.ajax({
                url: "@Url.Action("GetUnseenAnnouncements", "Announcement")",
                type: 'POST',
                cache: false
            }).done(function (data) {
                if (data) {
                    window.localStorage.setItem('AnnouncmentDataFetched', true);
                    window.localStorage.setItem('AnnouncementsData', JSON.stringify(data));
                }

                generateAnnouncementItems(data);
            });
        }
    };

    function generateAnnouncementItems(data) {
        let contentElement = $('.header-notification .notification-drawer .notification-drawer-content');
        contentElement.html("");

        if (!data) return;

        if (!window.location.pathname.startsWith('/Announcement')) {
            let unreadAnnouncements = data.filter(announcement => announcement.IsRead === false);
            $('.header-notification .icon-badge').text(unreadAnnouncements.length);
            if (unreadAnnouncements.length > 0)
                $('.header-notification .fa-bell').addClass('bell-animation');
        }

        for (let i = 0; i < data.length; i++) {
            let $item = $("<div class='notification-drawer-item'></div>");

            let $head = $("<div class='clearfix'></div>");
            $head.append("<span class='notification-drawer-item-title'>" + data[i].Title + "</span>");
            $head.append("<span class='notification-drawer-item-date'>" + data[i].DateString + "</span>");
            $item.append($head);

            if (data[i].Text) {
                $item.append("<div><span>" + formatAnnouncementContent(data[i].Text) + "</span></div>");
            }
            if (data[i].Url) {
                $item.append("<div><a href='" + data[i].Url + "'><strong>" + '@Loc.Link' + "</strong></span></div>");
            }

            contentElement.append($item);
        }
    }

    function formatAnnouncementContent(text) {
        var urlRegex = /(https?:\/\/[^\s]+)/g;
        return text.replace(urlRegex, function (url) {
            return '<a href="' + url + '" target="_blank">' + url + '</a>';
        }).replace(/(?:\r\n|\r|\n)/g, '<br>');
    }

    function setCookie(name, value, days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }

    function changeTheme(themeName) {
        $("body").removeClass(function (index, css) {
            // removes anything that starts with "theme-"
            return (css.match(/\btheme-\S+/g) || []).join(' ');
        });

        $("body").addClass("theme-" + themeName);

        localStorage.setItem('theme', themeName);
        setCookie('theme', themeName, 1);
    }

    window.onload = function () {
        let themeName = localStorage.getItem('theme');
        if (!themeName) return;
        if (document.cookie.indexOf('theme=' + themeName) > -1) return;

        setCookie('theme', themeName, 1);

        $("body").removeClass(function (index, css) {
            // removes anything that starts with "theme-"
            return (css.match(/\btheme-\S+/g) || []).join(' ');
        });
        $("body").addClass("theme-" + themeName);
    };

    function changeLanguage(language) {
        let url = new URL(window.location.href);
        url.searchParams.set('langId', language);

        $.ajax({
            url: $("#SaveLanguage").val(),
            method: 'POST',
            data: {
                language: language
            },
            success: function () {
            }
        });

        window.location.href = url;
    }

    window.addEventListener("load", loadNotifications, false);

    $(document).ready(function () {
        $('.dropdown-submenu a').on("click", function (e) {
            $(this).children(".dropdown-menu[style*='display: block']").toggle();
            $(this).next('ul').toggle();
            e.stopPropagation();
            e.preventDefault();
        });

        $('.dropdown-menu a').on("click", function (e) {
            if ($(this).closest("li").hasClass("dropdown-submenu")) {
                $(this).closest(".dropdown-menu").find(".dropdown-submenu").not($(this).closest("li")).children(".dropdown-menu").hide();
            }
        });
    });
</script>