<?php

namespace CelerSearch\Admin\Lists;

use CelerSearch\Indices\BaseIndex;
use CelerSearch\Repositories\ServiceRepository;

class Indices extends \WP_List_Table {

	protected $data;

	/**
	 * Constructor
	 */
	public function __construct() {
		parent::__construct( array(
			'singular' => 'index',
			'plural'   => 'indices',
			'ajax'     => false,
		) );
	}

	/**
	 * Set up the data.
	 *
	 * @param $data
	 *
	 * @return void
	 */
	public function set_data( $data ) {
		$this->data = $data;
	}

	/**
	 * The columns
	 * @return array
	 */
	public function get_columns() {
		return array(
			'title'   => __( 'Title', 'celersearch' ),
			'type'    => __( 'Type', 'celersearch' ),
			'service' => __( 'Service', 'celersearch' ),
			'actions' => __( 'Actions', 'celersearch' ),
		);
	}

	/**
	 * The actions column
	 *
	 * @param  BaseIndex  $item
	 *
	 * @return void
	 */
	protected function column_title( $item ) {
		return $item->get_name();
	}

	/**
	 * The actions column
	 *
	 * @param  BaseIndex  $item
	 *
	 * @return string
	 */
	protected function column_type( $item ) {
		return ucfirst( $item->get_type() );
	}

	/**
	 * The service column
	 *
	 * @param  BaseIndex  $item
	 *
	 * @return string
	 */
	protected function column_service( $item ) {
		$options = $item->get_options();
		$name    = __( 'Not set up yet', 'celersearch' );
		$repo    = new ServiceRepository();
		if ( ! empty( $options['service'] ) ) {
			$row  = $repo->find( (int) $options['service'] );
			$name = ucfirst( $row->name );
		}

		return esc_html($name);
	}

	/**
	 * The actions column
	 *
	 * @param  BaseIndex  $item
	 *
	 * @return string
	 */
	protected function column_actions( $item ) {

		if ( ! $item->is_configured() ) {
			return '<a class="button-secondary button-small" href="">' . __( 'Settings', 'celersearch' ) . '</a>';
		} else {
			return '<a class="button-primary button-small" href="">' . __( 'Setup', 'celersearch' ) . '</a>';
		}
	}

	/**
	 * Prepare items
	 * @return void
	 */
	public function prepare_items() {
		$columns               = $this->get_columns();
		$hidden                = array();
		$sortable              = $this->get_sortable_columns();
		$this->_column_headers = array( $columns, $hidden, $sortable );
		$this->items           = $this->data;
	}

	/**
	 * Disable table nav
	 *
	 * @param $which
	 *
	 * @return void
	 */
	protected function display_tablenav( $which ) {}
}