/**
  * List latest episodes from network
  * 
  * - limit:   Maximum number of episodes. Default: 10.
  * - orderby: Order episodes by 'post_date', 'post_title', 'ID' or 'comment_count'. Default: 'post_date'.
  * - order: Designates the ascending or descending order of the 'orderby' parameter. Default: 'DESC'.
  *   - 'ASC' - ascending order from lowest to highest values (1, 2, 3; a, b, c).
  *   - 'DESC' - descending order from highest to lowest values (3, 2, 1; c, b, a).
  * 
  * @accessor
  */
 public function episodes($args = array())
 {
     $number_of_episodes = isset($args['limit']) && is_numeric($args['limit']) ? $args['limit'] : 10;
     $orderby = isset($args['orderby']) && $args['orderby'] ? $args['orderby'] : 'post_date';
     $order = isset($args['order']) && $args['order'] ? $args['order'] : 'DESC';
     return $this->list->latest_episodes($number_of_episodes, $orderby, $order);
 }
 /**
  * Fetch all podcasts for Publisher blogs, ordered
  */
 public static function podcasts($sortby = "title", $sort = 'ASC')
 {
     $podcast_blog_ids = Network::podcast_blog_ids();
     if (empty($podcast_blog_ids)) {
         return [];
     }
     foreach ($podcast_blog_ids as $blog_id) {
         $podcasts[$blog_id] = Podcast::get($blog_id);
     }
     uasort($podcasts, function ($a, $b) use($sortby, $sort) {
         return strnatcmp($a->{$sortby}, $b->{$sortby});
     });
     if ($sort == 'DESC') {
         krsort($podcasts);
     }
     return $podcasts;
 }
    public static function right_now()
    {
        $podcasts = \Podlove\Modules\Networks\Model\Network::podcast_blog_ids();
        $number_of_podcasts = count($podcasts);
        if (!$number_of_podcasts) {
            echo __('No podcasts exist yet.', 'podlove');
            return;
        }
        $episodes_total = 0;
        $episodes_total_per_status = array('publish' => 0, 'private' => 0, 'future' => 0, 'draft' => 0);
        $episodes_total_length = 0;
        $episode_total_average_length = 0;
        $media_file_total_average_size = 0;
        $media_file_total_size = 0;
        $days_between_episodes = 0;
        foreach ($podcasts as $podcast) {
            switch_to_blog($podcast);
            $statistics = \Podlove\Settings\Dashboard\Statistics::prepare_statistics();
            $episodes_total += $statistics['total_number_of_episodes'];
            array_walk($statistics['episodes'], function ($posts, $type) use(&$episodes_total_per_status) {
                switch ($type) {
                    case 'publish':
                        $episodes_total_per_status['publish'] += $posts;
                        break;
                    case 'publish':
                        $episodes_total_per_status['private'] += $posts;
                        break;
                    case 'future':
                        $episodes_total_per_status['future'] += $posts;
                        break;
                    case 'draft':
                        $episodes_total_per_status['draft'] += $posts;
                        break;
                }
            });
            $episodes_total_length += $statistics['total_episode_length'];
            $episode_total_average_length += $statistics['average_episode_length'];
            $days_between_episodes += $statistics['days_between_releases'];
            $media_file_total_average_size += $statistics['average_media_file_size'];
            $media_file_total_size += $statistics['total_media_file_size'];
            restore_current_blog();
        }
        // Devide stats by number of Podcasts
        $episode_total_average_length /= $number_of_podcasts;
        $days_between_episodes /= $number_of_podcasts;
        $media_file_total_average_size /= $number_of_podcasts;
        ?>
		<div class="podlove-dashboard-statistics-wrapper">
			<h4>Episodes</h4>
			<table cellspacing="0" cellpadding="0" class="podlove-dashboard-statistics">
				<tr>
					<td class="podlove-dashboard-number-column">
						<?php 
        echo $episodes_total_per_status['publish'];
        ?>
					</td>
					<td>
						<span style="color: #2c6e36;"><?php 
        echo __('Published', 'podlove');
        ?>
</span>
					</td>
				</tr>
				<tr>
					<td class="podlove-dashboard-number-column">
						<?php 
        echo $episodes_total_per_status['private'];
        ?>
					</td>
					<td>
						<span style="color: #b43f56;"><?php 
        echo __('Private', 'podlove');
        ?>
</span>
					</td>
				</tr>
				<tr>
					<td class="podlove-dashboard-number-column">
						<?php 
        echo $episodes_total_per_status['future'];
        ?>
					</td>
					<td>
						<span style="color: #a8a8a8;"><?php 
        echo __('To be published', 'podlove');
        ?>
</span>
					</td>
				</tr>
				<tr>
					<td class="podlove-dashboard-number-column">
						<?php 
        echo $episodes_total_per_status['draft'];
        ?>
					</td>
					<td>
						<span style="color: #c0844c;"><?php 
        echo __('Drafts', 'podlove');
        ?>
</span>
					</td>
				</tr>
				<tr>
					<td class="podlove-dashboard-number-column podlove-dashboard-total-number">
						<?php 
        echo $episodes_total;
        ?>
					</td>
					<td class="podlove-dashboard-total-number">
						<?php 
        echo __('Total', 'podlove');
        ?>
					</td>
				</tr>
			</table>
		</div>
		<div class="podlove-dashboard-statistics-wrapper">
			<h4><?php 
        echo __('Statistics', 'podlove');
        ?>
</h4>
			<table cellspacing="0" cellpadding="0" class="podlove-dashboard-statistics">
				<tr>
					<td class="podlove-dashboard-number-column">
						<?php 
        echo gmdate("H:i:s", $episode_total_average_length);
        ?>
					</td>
					<td>
						<?php 
        echo __('is the average length of an episode', 'podlove');
        ?>
.
					</td>
				</tr>
				<tr>
					<td class="podlove-dashboard-number-column">
						<?php 
        $days = round($episodes_total_length / 3600 / 24, 1);
        echo sprintf(_n('%s day', '%s days', $days, 'podlove'), $days);
        ?>
					</td>
					<td>
						<?php 
        echo __('is the total playback time of all episodes', 'podlove');
        ?>
.
					</td>
				</tr>
				<tr>
					<td class="podlove-dashboard-number-column">
						<?php 
        echo \Podlove\format_bytes($media_file_total_average_size, 1);
        ?>
					</td>
					<td>
						<?php 
        echo __('is the average media file size', 'podlove');
        ?>
.
					</td>
				</tr>
				<tr>
					<td class="podlove-dashboard-number-column">
						<?php 
        echo \Podlove\format_bytes($media_file_total_size, 1);
        ?>
					</td>
					<td>
						<?php 
        echo __('is the total media file size', 'podlove');
        ?>
.
					</td>
				</tr>
				<tr>
					<td class="podlove-dashboard-number-column">
						<?php 
        echo sprintf(_n('%s day', '%s days', round($days_between_episodes), 'podlove'), round($days_between_episodes));
        ?>
					</td>
					<td>
						<?php 
        echo __('is the average interval until a new episode is released', 'podlove');
        ?>
.
					</td>
				</tr>
				<tr>
					<td class="podlove-dashboard-number-column">
						<?php 
        echo sprintf(_n('%s podcast', '%s podcasts', $number_of_podcasts, 'podlove'), $number_of_podcasts);
        ?>
					</td>
					<td>
						<?php 
        echo __('exist in your WordPress installation', 'podlove');
        ?>
.
					</td>
				</tr>
				<?php 
        do_action('podlove_dashboard_statistics_network');
        ?>
			</table>
		</div>
		<p>
			<?php 
        echo sprintf(__('You are using %s', 'podlove'), '<strong>Podlove Publisher ' . \Podlove\get_plugin_header('Version') . '</strong>');
        ?>
.
		</p>
		<?php 
    }
    public static function dashboard_network_statistics_row($genders)
    {
        $podcasts = \Podlove\Modules\Networks\Model\Network::podcast_blog_ids();
        $podcasts_with_contributors_active = 0;
        $relative_gender_numbers = array('male' => 0, 'female' => 0, 'none' => 0);
        foreach ($podcasts as $podcast) {
            switch_to_blog($podcast);
            if (\Podlove\Modules\Base::is_active('contributors')) {
                $global_gender_numbers = self::fetch_contributors_for_dashboard_statistics();
                if ($global_gender_numbers['global']['total'] > 0) {
                    foreach ($global_gender_numbers['global']['by_gender'] as $gender => $number_of_contributions) {
                        $relative_gender_numbers[$gender] += $number_of_contributions / $global_gender_numbers['global']['total'] * 100;
                    }
                }
                $podcasts_with_contributors_active++;
            }
            restore_current_blog();
        }
        ?>
		<tr>
			<td class="podlove-dashboard-number-column">
				<?php 
        echo __('Genders', 'podlove');
        ?>
			</td>
			<td>
				<?php 
        echo implode(', ', array_map(function ($percent, $gender) use($podcasts_with_contributors_active) {
            return round($percent / $podcasts_with_contributors_active) . "% " . ($gender == 'none' ? 'not attributed' : $gender);
        }, $relative_gender_numbers, array_keys($relative_gender_numbers)));
        ?>
			</td>
		</tr>
		<?php 
    }
 public function prepare_items()
 {
     // define column headers
     $columns = $this->get_columns();
     $hidden = array();
     $sortable = false;
     $this->_column_headers = array($columns, $hidden, $sortable);
     $items = Network::podcasts();
     uasort($items, function ($a, $b) {
         return strnatcmp($a->title, $b->title);
     });
     $this->items = $items;
 }
    private function form_template($list, $action, $button_text = NULL)
    {
        $form_args = array('context' => 'podlove_list', 'hidden' => array('list' => $list->id, 'action' => $action));
        \Podlove\Form\build_for($list, $form_args, function ($form) {
            $wrapper = new \Podlove\Form\Input\TableWrapper($form);
            $list = $form->object;
            $wrapper->string('slug', array('label' => __('ID', 'podlove'), 'html' => array('class' => 'regular-text required'), 'description' => sprintf(__('For referencing in templates: %s', 'podlove'), '<code>{{ network.lists({id: "example"}).title }}</code>')));
            $wrapper->string('title', array('label' => __('Title', 'podlove'), 'html' => array('class' => 'regular-text required')));
            $wrapper->string('subtitle', array('label' => __('Subtitle', 'podlove'), 'html' => array('class' => 'regular-text')));
            $wrapper->text('description', array('label' => __('Summary', 'podlove'), 'description' => __('', 'podlove'), 'html' => array('rows' => 3, 'cols' => 40, 'class' => 'autogrow')));
            $wrapper->image('logo', array('label' => __('Logo', 'podlove'), 'description' => __('JPEG or PNG.', 'podlove'), 'html' => array('class' => 'regular-text'), 'image_width' => 300, 'image_height' => 300));
            $wrapper->string('url', array('label' => __('List URL', 'podlove'), 'description' => __('', 'podlove'), 'html' => array('class' => 'regular-text')));
            $wrapper->callback('podcasts', array('label' => __('Podcasts', 'podlove'), 'callback' => function () use($list) {
                $form_base_name = "podlove_list";
                ?>
					<div id="podcast_lists">
						<table class="podlove_alternating" border="0" cellspacing="0">
							<thead>
								<tr>
									<th><?php 
                echo __('Source', 'podlove');
                ?>
</th>
									<th><?php 
                echo __('Podcast/URL', 'podlove');
                ?>
</th>
									<th style="width: 60px"><?php 
                echo __('Remove', 'podlove');
                ?>
</th>
									<th style="width: 30px"></th>
								</tr>
							</thead>
							<tbody class="podcasts_table_body" style="min-height: 50px;">
								<tr class="podcasts_table_body_placeholder" style="display: none;">
									<td><em><?php 
                echo __('No Podcasts were added yet.', 'podlove');
                ?>
</em></td>
								</tr>
							</tbody>
						</table>

						<div id="add_new_podcasts_wrapper">
							<input class="button" id="add_new_podcast" value="+" type="button" />
						</div>

						<script type="text/template" id="podcast-row-template">
						<tr class="media_file_row podlove-podcast-table" data-id="{{id}}">
							<td class="podlove-podcast-column">
								<select name="<?php 
                echo $form_base_name;
                ?>
[podcasts][{{id}}][type]" class="podlove-podcast-dropdown">
									<option value="wplist" selected><?php 
                echo __('WordPress Network', 'podlove');
                ?>
</option>
								</select>
							</td>
							<td class="podlove-podcast-value"></td>
							<td>
								<span class="podcast_remove">
									<i class="clickable podlove-icon-remove"></i>
								</span>
							</td>
							<td class="move column-move"><i class="reorder-handle podlove-icon-reorder"></i></td>
						</tr>
						</script>
						<script type="text/template" id="podcast-select-type-wplist">
						<select name="<?php 
                echo $form_base_name;
                ?>
[podcasts][{{id}}][podcast]" class="podlove-podcast chosen-image">
							<option>— <?php 
                echo __('Select Podcast', 'podlove');
                ?>
 —</option>
							<?php 
                foreach (Network::podcasts() as $blog_id => $podcast) {
                    if ($podcast->title) {
                        printf("<option value='%s' data-img-src='%s'>%s</option>\n", $blog_id, $podcast->cover_art()->setWidth(45)->url(), $podcast->title);
                    }
                }
                ?>
						</select>
						</script>
					</div>

					<script type="text/javascript">

						var PODLOVE = PODLOVE || {};

						(function($) {
							var i = 0;
							var existing_podcasts = <?php 
                echo is_null($list->podcasts) ? "[]" : $list->podcasts;
                ?>
;
							var podcasts = [];

							function update_chosen() {
								$(".chosen").chosen();
								$(".chosen-image").chosenImage();
							}

							function podcast_dropdown_handler() {
								$('select.podlove-podcast-dropdown').change(function() {
									row = $(this).closest("tr");
									podcast_source = $(this).val();

									// Check for empty podcast / for new field
									if (podcast_source === '') {
										row.find(".podlove-podcast-value").html(""); // Empty podcast column and hide edit button
										row.find(".podlove-podcast-edit").hide();
										return;
									}

									if (!row.find(".podlove-podcast").length) {
										template_id = "#podcast-select-type-" + podcast_source;
										template = $( template_id ).html();
										template = template.replace(/\{\{id\}\}/g, row.data('id') );

										row.find(".podlove-podcast-value").html( template );
										update_chosen();

										i++; // continue using "i" which was already used to add the existing contributions
									}

								});
							}

							$(document).ready(function() {
								$("#podcast_lists table").podloveDataTable({
									rowTemplate: "#podcast-row-template",
									deleteHandle: ".podcast_remove",
									sortableHandle: ".reorder-handle",
									addRowHandle: "#add_new_podcast",
									data: existing_podcasts,
									dataPresets: podcasts,
									onRowLoad: function(o) {
										template_id = "#podcast-select-type-" + o.entry.type;
										template = $( template_id ).html();
										row_as_object = $(o.row)
										
										row_as_object.find(".podlove-podcast-value").html( template );
										row_as_object.find('select.podlove-podcast-dropdown option[value="' + o.entry.type + '"]').attr('selected', 'selected');

										switch ( o.entry.type ) {
											default: case 'wplist':
												row_as_object.find('select.podlove-podcast option[value="' + o.entry.podcast + '"]').attr('selected', true);
											break;
										}

										o.row = row_as_object[0].outerHTML.replace(/\{\{id\}\}/g, i);

										i++;
									},
									onRowAdd: function(o) {
										o.row = o.row.replace(/\{\{id\}\}/g, i);

										
										row = $(".podcasts_table_body tr:last .podlove-podcast-dropdown").focus();

										podcast_dropdown_handler();
										update_chosen();
										row.change();
									},
									onRowDelete: function(tr) {
										
									}
								});
							});

						}(jQuery));

					</script>
					<?php 
            }));
        });
    }
 private static function podcast_ids()
 {
     return Model\PodcastList::with_network_scope(function () {
         return Model\Network::podcast_blog_ids();
     });
 }