<?php

namespace DashNex\SiteManager\Model;

class PrimaryKeywordNode extends SMActionCaller {

	const OPT_NAME = '_dashnex-primary-keyword-node';

	protected $keyword;
	protected $wp_page_id;

	private $category_keywords;
	private $wp_page;

	public function __construct() {
		$this->init();
	}

	public function GetKeyword() { 
		return $this->keyword;
	}

	public function SetKeyword($keyword) {
		$this->keyword = $keyword;
		return $this;
	}

	public function GetWPPageId() {
		return $this->wp_page_id;
	}

	public function SetWPPageId($id) {
		$this->wp_page_id = $id;
		$this->wp_page = null;
		return $this;
	}

	public function GetCategoryKeywords($flat = false) {
		global $dashnex_service_manager;

		if($this->category_keywords === null) {
			$categoryKeywordMgr = $dashnex_service_manager->getService('dashnex-category-keyword-manager');
			$this->category_keywords = $flat
				? $categoryKeywordMgr->GetCategoryKeywordNodes()
				: $categoryKeywordMgr->GetCategoryKeywordNodesByParent(null);
			if($flat) {
				var_dump($flat);
				var_dump($this->category_keywords);die;
			}
		}

		return $this->category_keywords;
	}

	public function GetWPPage($output = 'OBJECT') {
		if($this->wp_page === null && $this->GetWPPageId() > 0) {
			$this->wp_page = get_post($this->GetWPPageId(), $output);
		} else if( ! $this->GetWPPageId() && $this->wp_page) {
			$this->wp_page = null;
		}

		return $this->wp_page;
	}

	// ActionCaller interface methods

	public function GetCallerType() {
		return 'primary-keyword';
	}

	// ActionCaller interface methods END

	public function LoadDataArray($data) {
		if( ! is_array($data)) {
			return;
		}
		if(isset($data['keyword'])) {
			$this->SetKeyword($data['keyword']);
		}
		if(isset($data['wp_page_id'])) {
			$this->SetWPPageId($data['wp_page_id']);
		}
	}

	public function Save() {
		$data = $this->GetDataArray();
		update_option(self::OPT_NAME, $data);
	}

	public function Remove($leaveWPObjects = false) {
		if($this->GetWPPageId() > 0 && ! $leaveWPObjects) {
			wp_delete_post($this->GetWPPageId(), true);
		}
		delete_option(self::OPT_NAME);
	}

	protected function init() {
		$opts = get_option(self::OPT_NAME, array());
		$this->LoadDataArray($opts);
	}

}