<?php

namespace Hura8\System\Controller;

use Hura8\System\Model\RelationModel;
use Hura8\Traits\ClassCacheTrait;

class RelationController
{
    use ClassCacheTrait;

    protected  $objRelationModel;

    private $main_item_type = '';
    private $main_item_id = 0;

    public function __construct($main_item_type, $main_item_id)
    {
        $this->objRelationModel = new RelationModel($main_item_type, $main_item_id);
        $this->main_item_type = $main_item_type;
        $this->main_item_id = $main_item_id;
    }


    public function updateOrdering($related_item_id, $new_order) {
        return $this->objRelationModel->updateOrdering($related_item_id, $new_order);
    }


    //@warn: this does not check if records exist.
    public function create(array $related_items, $both_way_relation = true) {
        return $this->objRelationModel->create($related_items, $both_way_relation);
    }


    public function checkExist($main_item_type, $main_item_id, $related_item_type, $related_item_id){
        return $this->objRelationModel->checkExist($main_item_type, $main_item_id, $related_item_type, $related_item_id);
    }

    //remove a related-item
    public function remove($related_item_type, $related_item_id, $remove_both_way = true) {
        return $this->objRelationModel->remove($related_item_type, $related_item_id, $remove_both_way);
    }


    //remove all relate items
    public function truncate() {
        $this->objRelationModel->truncate();
    }


    public function getRelatedItems(array $related_item_types = []) {
        return $this->objRelationModel->getRelatedItems($related_item_types);
    }

    public function getRelatedItemsForList(array $main_item_list_ids, array $related_item_types = []) {
        return $this->objRelationModel->getRelatedItemsForList($main_item_list_ids, $related_item_types);
    }

    //count related items
    public function getRelatedItemCount() {
        return $this->objRelationModel->getRelatedItemCount();
    }

    public static function findItemUrl($item_type, $item_id) {
        $url_config = array(
            "product"           => "/admin/?opt=product&view=form&id=".$item_id."&part=relation&l=vi&popup=".POPUP,
            "product-category"  => "?opt=product&view=category-form&id=".$item_id."",

            "article-article"   => "?opt=article&view=form&id=".$item_id."&l=&popup=".POPUP,
            "article-category"   => "?opt=article&view=category-form&id=".$item_id."&l=&popup=".POPUP,

            "album"             => "?opt=album&view=form&id=".$item_id,
            "banner"            => "?opt=banner&view=upload&id=".$item_id,
            "page"              => "?opt=page&view=form&id=".$item_id,
        );

        return (isset($url_config[$item_type])) ? $url_config[$item_type] : null;
    }


}
