<?php namespace Intellex\MailChimp\Api;

use Intellex\MailChimp\Resource\ResourceTemplate;
use Intellex\Curly\Method;

/**
 * Class ListApi
 *  Handles all templates API operations.
 *
 * @package Intellex\MailChimp\Api
 */
class ApiTemplates extends ApiAbstract {

	/**
	 * Get all of the list for the account.
	 *
	 * @return ResourceTemplate[] The list of found templates.
	 */
	public function getAll() {
		$data = $this->curl('templates')->getContent();

		// Convert
		$templates = [];
		foreach ($data['templates'] as $template) {
			$templates[] = new ResourceTemplate($template);
		}

		return $templates;
	}

	/**
	 * Get a list by its unique ID.
	 *
	 * @param string $templateId The unique ID of the template.
	 *
	 * @return ResourceTemplate The found template, or null if not found.
	 */
	public function get($templateId) {

		// Check if list exists
		$templates = $this->getAll();
		foreach ($templates as $template) {
			if ($template->getId() == $templateId) {
				return $template;
			}
		}

		return null;
	}

	/**
	 * Get a list by its unique ID.
	 *
	 * @param string $templateId The unique ID of the template.
	 *
	 * @return array $data
	 */
	public function defaultContent($templateId) {
		$data = $this->curl(['templates', $templateId, 'default-content'])->getContent();

		return $data;
	}

	/**
	 * Edit template
	 *
	 * @param string $name name of the new template.
	 * @param string $html generated html.
	 * @param string $templateId unique Id of the template
	 *
	 * @return \Intellex\Curly\Response $response
	 */
	public function edit($name, $html, $templateId) {

		$data = [
			'name' => $name,
			'html' => $html
		];

		$response = $this->curl(['templates', $templateId], $data, Method::PATCH)->getContent();

		return $response;
	}

	/**
	 * Create new template
	 *
	 * @param string $name name of the new template.
	 * @param string $html generated html.
	 *
	 * @return \Intellex\Curly\Response $response
	 */
	public function create($name, $html) {

		$data = [
			'name' => $name,
			'html' => $html
		];

		$response = $this->curl('templates', $data)->getContent();

		return $response;
	}
}