<%
  permission = User.current.allowed_to_globally?(:view_easy_calendar)
  time = Time.now
  user = User.current
  if permission
    meetings = EasyMeeting.arel_table
    event = EasyMeeting.includes(:easy_invitations).where(easy_invitations: {user_id: user.id}).
        where(easy_invitations: {accepted: true}).
        where(meetings[:start_time].gt(time)).
        order(:start_time).first
  end
%>

<div class="easy-calendar-upcoming">
  <% if permission %>
    <div class="easy-calendar-upcoming__calendar">
      <%= link_to('javascript:void(0)', {
          onclick: %Q{if (!this.classList.contains("w-toggleable__trigger--active")){$.get("#{raw mini_easy_calendar_path(format: 'js')}");}},
          remote: true, class: 'easy-calendar-upcoming__calendar-trigger', title: l(:easy_calendar_plugin_name)
      }) do %>
        <i class="icon-calendar"></i>
      <% end %>
      <div class="easy-calendar-upcoming__calendar-content">
      </div>
    </div>
  <% end %>
  <div class="easy-calendar-upcoming__texts">
    <span class="easy-calendar-upcoming__current-time">
    </span>
    <% if permission %>
      <span class="easy-calendar-upcoming__event">
        <% if event %>
          <%= l :label_upcoming_meeting %>
          <%= link_to(easy_meeting_path(event),
                      onclick: %Q{event.preventDefault(); $.get(this.href, {}, function(r){$("#ajax-modal").html(r); showModal('ajax-modal')});}) do %>
            <%= format_hours((event.start_time - time) / 1.hour, no_html: true, format: 'long') %>
          <% end %>
        <% else %>
          <%= l :label_upcoming_none %>
        <% end %>
      </span>
    <% end %>
    <span class="block"></span>
    <span class="easy-calendar-upcoming__current-date"><%= format_date(time) %></span>
    <% if permission %>
      <% if event %>
        <span class="easy-calendar-upcoming__event">
          <%= link_to(easy_meeting_path(event),
                      onclick: %Q{event.preventDefault(); $.get(this.href, {}, function(r){$("#ajax-modal").html(r); showModal('ajax-modal')});}) do %>
            <%= truncate event.name, length: 60 %>
          <% end %>
        </span>
      <% end %>
    <% end %>
  </div>
</div>
<script>
  !function easyCalendarGetTime() {
    var d = new Date();
    $(".easy-calendar-upcoming__current-time").html(d.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}));
    $(".easy-calendar-upcoming__current-date").html(d.toLocaleDateString());
    setTimeout(easyCalendarGetTime, 60000);
  }();
</script>
