{#
 # _macros.html
 #
 # Copyright © 2013-2017 Antergos
 #
 # This file is part of The Antergos Build Server, (AntBS).
 #
 # AntBS is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 3 of the License, or
 # (at your option) any later version.
 #
 # AntBS is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 # GNU General Public License for more details.
 #
 # The following additional terms are in effect as per Section 7 of the license:
 #
 # The preservation of all legal notices and author attributions in
 # the material or in the Appropriate Legal Notices displayed
 # by works containing it is required.
 #
 # You should have received a copy of the GNU General Public License
 # along with AntBS; If not, see <http://www.gnu.org/licenses/>.
 #}

{# Macros (Reusable Code Snippets) #}


{#
 # Generates navigation menu items and adds "active" class for current page.
 #
 # Args:
 #     endpoint (str):   The link url relative to root.
 #     text: (str):      The link text.
 #     icon_class (str): The css class for the menu icon.
 #     active_class (str): The css class applied to the active menu item.
 #     _class (str): Optional extra css class to add to the menu item.
 #}
{% macro nav_link(endpoint, text, icon_class='', active_class='', is_heading=False) %}
	{% if request.path == endpoint and not is_heading %}
		{% set active_class = 'active' %}
	{% elif is_heading %}
		{% set active_class = 'submenu_heading' %}
	{% endif %}

	<li class="{{ active_class }}">
		<a href="{{ endpoint }}">
			{% if not is_heading %}
				<i class="fa fa-{{ icon_class }}"></i>
			{% endif %}
			<span>{{ text }}</span>
		</a>
	</li>
{% endmacro %}


{#
 # Generates page heading and breadcrumbs.
 #
 # Args:
 #     pagetitle (str): The title text for the page.
 #
 #}
{% macro page_heading(pagetitle) %}
	{% if request.path != "/" %}
		<div class="page-head">
			<h2>{{ pagetitle }}</h2>
			<ol class="breadcrumb">
				<li><a href="/">Home</a></li>
				<li class="active">{{ pagetitle }}</li>
			</ol>
		</div>
	{% endif %}
{% endmacro %}


{#
 # Generates HTML (& JavaScript) for a calendar heatmap chart.
 #
 # Args:
 #     data (list): The data for the chart as a list of dicts.
 #     selector (str): CSS selector for the heatmap container.
 #
 #}
{% macro calendar_heatmap(data, selector) %}
	<script type="text/javascript" src="//d3js.org/d3.v3.min.js"></script>
	<script src="/static/js/calendar_heatmap.bundle.js"></script>
	<script>
		$(window).load(function () {
			var history = $.parseJSON('{{ data|safe() }}');

			calendar_heatmap.create({
				data: history,
				date_var: 'date',
				fill_var: 'builds',
				target: '{{ selector }}',
				missing_as_zero: true,
				sunday_start: true,
				date_format: '%m-%d-%Y',
				color_scheme: calendar_heatmap.color_ramps.RdPu,
				abbr_weekdays: true,
				number_format: 'g',
				tile_width: 12,
				tile_height: 13,
				stroke_color: '#383A41',
				unselected_color: '#FAA6B7',
				accent_color: '#ffffff',
				show_toggle: false,
				margin_top: 30,
				margin_bottom: 0
			});
		});
	</script>
{% endmacro %}


{#
 # Generates HTML (& JavaScript) for activating custom toggles/switches.
 #
 #}
{%- macro toggles_init() -%}
	<script type="text/javascript" src="/static/js/bootstrap-switch.min.js"></script>
	<script>
		(function($) {
			$(window).load(function() {
				var $inside_tab = $('.tab-pane:not(.active) .switch');

				if ($inside_tab.length) {
					$('a[data-toggle="tab"]').on('shown.bs.tab', function() {
						var target = $(this).attr('href');
						$(target).find('.switch').bootstrapSwitch();
						$(this).off('shown.bs.tab');
					});
				} else {
					$('.switch').bootstrapSwitch();
				}
			});
		})(jQuery);
	</script>
{%- endmacro -%}


{#
 # Generates HTML for a build activity timeline.
 #
 # Args:
 #     tl_events (list): The data for the timeline as a list of `TimelineEvent` objects.
 #     all_pages (int): Number of pages available.
 #     page (int): The current page.
 #
 #}
{% macro build_activity_timeline(tl_events, all_pages, page) %}
	{% set icons = ['fa-bolt', 'fa-github', 'phab', 'fa-rocket', 'fa-check', 'fa-times', 'fa-comment'] %}
	<div class="block-transparent tlwrap">
		<div class="header">
			<h4>Timeline</h4>
		</div>

		<ul class="timeline">
			{%- for event in tl_events %}
				<li id="{{ event.event_id }}">
					<i class="fa {{ icons[event.tl_type] }}"></i>
					<span class="date">{{ event.date_str }}</span>

					<div class="content" style="padding-bottom:3px;">
						{{ event.message|safe() }}

						<p style="margin-top:10px;padding-bottom: 0px;">
							<small>{{ event.time_str }}</small>
							{% if current_user.is_authenticated and event.packages|count() > 0 %}
								<a href="#" class="rerun-transaction" data-tlevent="{{ event.event_id }}">
									<i class="fa fa-repeat" data-toggle="tooltip" title="Rerun This Transaction"></i>
								</a>
							{% endif %}
						</p>

					</div>

				</li>
			{% endfor -%}
		</ul>

		{% if all_pages > 1 %}
			<ul class="pagination">
				{% if page >= 2 %}
					<li><a href="/timeline/{{ page - 1 }}">&laquo;</a></li>
				{% else %}
					<li class="disabled"><a href="#">&laquo;</a></li>
				{% endif %}

				<li class="active"><a href="#">{{ page }}</a></li>
				<li><a href="/timeline/{{ page + 1 }}">&raquo;</a></li>
			</ul>
		{% endif %}
	</div>
{% endmacro %}


{#
 # Generates HTML for simple counters like the ones on the package profile pages.
 #
 # Args:
 #     number (int): The number for the counter to display.
 #     title_text (str): The title for the counter.
 #     color_class (str): Color class (primary, success, danger, etc)
 #     column_size (str): The column size that the counter will be wrapped with.
 #
 #}
{% macro simple_counter(number, title_text, color_class, column_size='4') %}
	{% if '' != color_class %}
		{% set color_class = 'text-' + color_class %}
	{% endif %}
	<div class="col-md-{{ column_size }} simple_counter {{ color_class }}">
		<h3>{{ title_text }}</h3>
		{{ number }}
	</div>
{% endmacro %}


{#
 # Generates HTML for styled a label/tag link.
 #
 # Args:
 #     url_base (str): The first part of the URL to link to.
 #     url_end (str): The last part of the URL to link to.
 #     text (str): The text for the tag/label.
 #     color_class (str): Color class (primary, success, danger, etc)
 #
 #}
{% macro label_tag_link(url_base, url_end, text, color_class) %}
	<a href="{{ url_base }}{{ url_end }}" class="label label-{{ color_class }}">{{ text }}</a>
{% endmacro %}


{#
 # Generates HTML for pagination links.
 #
 # Args:
 #     pagination (Pagination): `Pagination` object for the table.
 #
 #}
{% macro render_pagination(pagination) %}
	<ul class="pagination custom">
		{% if pagination.has_prev %}
			<li><a href="{{ url_for_other_page(pagination.page - 1) }}">&laquo; Previous</a></li>
		{% endif %}
		{%- for page in pagination.iter_pages() %}
			{% if page %}
				{% if page != pagination.page %}
					<li><a href="{{ url_for_other_page(page) }}">{{ page }}</a></li>
				{% else %}
					<li class="active"><a href="#"><strong>{{ page }}</strong></a></li>
				{% endif %}
			{% else %}
				<li><span class=ellipsis>…</span></li>
			{% endif %}
		{%- endfor %}
		{% if pagination.has_next %}
			<li><a href="{{ url_for_other_page(pagination.page + 1) }}">Next &raquo;</a></li>
		{% endif %}
	</ul>
{% endmacro %}


{#
 # Generates HTML for package/build/mirror listing table search box.
 #
 #}
{% macro table_search_box() %}
	<div class="col-md-3 pull-right">
		<div class="form-group">
			<div class="input-group">
				<label for="search_input" class="sr-only">Search</label>
				<input id="search_input" type="text" class="form-control"/>
				<span class="input-group-btn">
					<button id="search_btn" class="btn btn-primary" type="button">Search!</button>
				</span>
			</div>
		</div>
	</div>
{% endmacro %}


{#
 # Generates HTML for action/review_result dropdown (Logged-in users only).
 #
 # Args:
 #    obj (Package|Build):       The `Package` or `Build` object for the dropdown.
 #    dd_info (dict):            A dict containing info for dropdown:
 #        dd_type    (str):         The type of dropdown ('Action' or 'Set Result').
 #        menu_items (list[dict]):  List of dicts containing menu items' class, icon class, color, and label text.
 #        dd_class   (str):         CSS class(es) for the menu.
 #
 #}
{% macro table_dropdown(obj, dd_info) %}
	{% if current_user.is_authenticated %}

		{% if 'Action' == dd_type %}
			{% set bnum = obj._build.bnum %}
		{% else %}
			{% set bnum = obj.bnum %}
		{% endif %}

		<div class="btn-group">
			<button class="btn btn-default btn-xs" type="button">{{ dd_info.dd_type|capitalize() }}</button>
			<button data-toggle="dropdown" class="btn btn-xs btn-primary dropdown-toggle" type="button">
				<span class="caret"></span><span class="sr-only">Toggle Dropdown</span>
			</button>
			<ul role="menu" class="dropdown-menu {{ dd_info.dd_class }}">
				{% if dd_info.menu_items and dd_info.menu_items is iterable %}
					{% for menu_item in dd_info.menu_items %}
						<li>
							<a href="#" class="{{ menu_item['link_class'] }}" data-bnum="{{ bnum }}" data-pkg="{{ obj.pkgname }}">
								<i class="fa fa-{{ menu_item['icon_class'] }}" style="color:{{ menu_item['icon_color'] }};"></i> {{ menu_item['text'] }}
							</a>
						</li>
					{% endfor %}
				{% endif %}
			</ul>
		</div>
	{% endif %}
{% endmacro %}


{#
 # Generates HTML for text with icon.
 #
 # Args:
 #     icon_info  (dict): Dict which maps one or more icon_class(es) & icon_color(s) to possible `text` values.
 #     text       (str):  The text to display next to the icon. Not required when calling this
 #                        macro from another macro. You should place text inside call block instead.
 #}
{% macro text_with_icon(icon_info, text=None, icon_class_key=None) %}
	{% set icon_class = icon_info.class %}
	{% set icon_color = icon_info.color %}

	{% if icon_info.class is mapping and icon_class_key is not none %}
		{% set icon_class = icon_info.class[icon_class_key] %}
	{% elif icon_info.class is mapping %}
		{% set icon_class = icon_info.class[text] %}
	{% endif %}

	{% if icon_info.color is mapping and icon_class_key is not none %}
		{% set icon_color = icon_info.color[icon_class_key] %}
	{% elif icon_info.color is mapping %}
		{% set icon_color = icon_info.color[text] %}
	{% endif %}

	<i class="fa fa-{{ icon_class }}" style="color: {{ icon_color }}"></i> {{ text }}
{% endmacro %}


{#
 # Generates HTML for package/build/mirror listing table.
 #
 # Args:
 #     columns_info   (list[dict]):                 List of dicts containing info for each column. Dict keys expected
 #                                                  are heading_text, obj_attr, content_type, base_url, dd_info
 #     objs           (list[Package|Build|Mirror]): List of `Package`|`Build`|`Mirror` objects to be listed in table.
 #     pagination     (Pagination):                 The `Pagination` object for the table.
 #     search_enabled (bool):                       Whether or not search box should be output for the table.
 #}
{% macro listing_table(columns_info, objs, pagination, search_enabled=True) %}
	{% if search_enabled %}
		{{ table_search_box() }}
	{% endif %}

	<table class="table no-border hover">
		<thead class="no-border">
			<tr>
				{% for column in columns_info %}
					<td>{{ column.heading_text }}</td>
				{% endfor %}
			</tr>
		</thead>
		<tbody class="no-border-y">
			{% if objs and objs is iterable %}
				{% for obj in objs %}
					<tr>
						{% for column in columns_info %}
							{% set _class = column.heading_text|replace(' ', '')|lower() %}
							<td class="{{ _class }}">
								{% if column.obj_attr and '.' in column.obj_attr %}
									{% set obj_attr, nested_obj_attr = column.obj_attr.split('.') %}
									{% set value = obj|attr(obj_attr) %}
									{% set value = value|attr(nested_obj_attr) %}

								{% elif column.obj_attr is sequence and column.obj_attr is not string %}
									{% set value = [] %}
									{% for val in column.obj_attr %}
										{% do value.append(obj|attr(val)) %}
									{% endfor %}

								{% elif column.obj_attr %}
									{% set value = obj|attr(column.obj_attr) %}

								{% elif 'Group' == column.heading_text %}
									{% set value = column.group %}
								{% endif %}

								{%- if not value and 'dropdown' != column.content_type -%}
									-

								{%- elif 'link' == column.content_type %}
									{% if value is not string and value is sequence %}
										<a href="{{ column.base_url }}{{ value[0] }}/{{ value[1] }}">{{ value[1] }}</a>
									{% else %}
										<a href="{{ column.base_url }}{{ value }}">{{ value }}</a>
									{% endif %}

								{% elif 'link_with_icon' == column.content_type %}
									{% if 'Last Build' == column.heading_text and True == value|int()|build_failed() %}
										{% set class_name_key = 'failed' %}
									{% elif 'Last Build' == column.heading_text %}
										{% set class_name_key = 'completed' %}
									{% else %}
										{% set class_name_key = None %}
									{% endif %}
									<a href="{{ '/build/%s'|format(value) }}">
										{{ text_with_icon(column.icon_info, value, class_name_key) }}
									</a>

								{% elif 'text_with_icon' == column.content_type %}
									{{ text_with_icon(column.icon_info, value) }}

								{% elif 'text' == column.content_type %}
									{{ value }}

								{% elif 'dropdown' == column.content_type and 'dd_info' in column %}
									{{ table_dropdown(obj, column.dd_info) }}

								{% elif 'label_tag_link' == column.content_type %}
									{% if value is not string and value is sequence %}
										{% set url_end = '%s/%s'|format(value[0], value[1]) %}
										{{ label_tag_link(column.base_url, url_end, value, column.color_class) }}
									{% else %}
										{{ label_tag_link(column.base_url, value, value, column.color_class) }}
									{% endif %}
								{% endif %}
							</td>
						{% endfor %}
					</tr>
				{% endfor %}
			{% endif %}
		</tbody>
	</table>
	{% if all_pages > 1 %}
		{{ render_pagination(pagination) }}
	{% endif %}
{% endmacro %}


{#
 # Generates JavaScript for listing table search box event handlers.
 #
 #}
{% macro table_search_box_js() %}
	<script>
		(function($) {
			$('#search_btn').on('click', function() {
				var search = $('#search_input').val(),
					path = window.location.pathname.split('/'),
					_ = path.splice(4),
					path = path.join('/');

				window.location.pathname = path + '/search/' + search;
			});

			$("#search_input").keyup(function(e) {
				if (e.keyCode == 13) {
					$('#search_btn').trigger('click');
				}
			});
		})(jQuery);
	</script>
{% endmacro %}


{#
 # Generates HTML for list groups with items containing two columns.
 #
 # Args:
 #     items (list[tuples]): List of tuples which contain the column contents for each list group item.
 #
 #}
{% macro list_group(items, column_sizes=['6', '6']) %}
	{% if items is iterable %}
		<div class="list-group">
			{% for item in items %}
				<div class="list-group-item">
					<div class="row">
						<div class="col-md-{{ column_sizes[0] }}">
							<p>{{ item[0] }}:</p>
						</div>
						<div class="col-md-{{ column_sizes[1] }}">
							{% if 'Status' != item[0] %}
								<p>{{ item[1] }}</p>
							{% else %}
								{{ item[1] }}
							{% endif %}
						</div>
					</div>
				</div>
			{% endfor %}
		</div>
	{% endif %}
{% endmacro %}


{#
 # Outputs "readonly" if condition evaluates to a truthy value.
 #
 # Args:
 #     condition (mixed): If condition is truthy, output "readonly".
 #
 #}
{%- macro readonly(condition) -%}
	{%- if condition -%}
		readonly
	{%- endif -%}
{%- endmacro -%}


{#
 # Outputs `text` if condition evaluates to a truthy value.
 #
 # Args:
 #     condition (mixed): If condition is truthy, output "checked".
 #     text      (str):   The text to output. Not required when calling this macro from another macro;
 #                        you should place text inside call block instead.
 #
 #}
{%- macro conditional_text(condition, text=None) -%}
	{% if text is none %}
		{% set text = caller() %}
	{% endif %}
	{%- if condition -%}
		{{ text }}
	{%- endif -%}
{%- endmacro -%}


{#
 # Outputs HTML for toggle switch (input) field.
 #
 # Args:
 #     on_text           (str):   Text displayed when toggle is "checked".
 #     off_text          (str):   Text displayed when toggle is not "checked".
 #     ro_condition      (mixed): If condition is truthy, mark the toggle input as "readonly".
 #     checked_condition (mixed): If condition is truthy, mark the toggle input as "checked".
 #
 #}
{%- macro toggle_switch(on_text='ON', off_text='OFF', ro_condition=False, checked_condition=False) -%}
	<input class="switch" type="checkbox" data-on-color="info" data-on-text="{{ on_text }}" data-off-text="{{ off_text }}"
		{%- call conditional_text(ro_condition) -%}readonly {% endcall -%}
		{%- call conditional_text(checked_condition) -%}checked {% endcall -%} />
{%- endmacro -%}
