<?php

namespace Drupal\basket;

class BasketTerm{
    protected static $tree;
    protected static $terms;
    protected static $getColorOptions;
    protected static $Basket;

    public function __construct(){
        if(empty(self::$Basket)){
            self::$Basket = \Drupal::service('Basket');
        }
    }

  	public function tree($type){
  		if(!isset(self::$tree[$type])){
	  		self::$tree[$type] = \Drupal::database()->select('basket_terms', 't')
	  								->fields('t')
	  								->condition('t.type', $type)
	  								->orderBy('t.weight', 'ASC')
	  								->orderBy('t.name', 'ASC')
	  								->execute()->fetchAll();
  		}
  		return self::$tree[$type];
  	}
  	public function load($tid){
  		if(!isset(self::$terms[$tid])){
	  		self::$terms[$tid] = \Drupal::database()->select('basket_terms', 't')
	  								->fields('t')
	  								->condition('t.id', $tid)
	  								->execute()->fetchObject();
            self::colorAlter(self::$terms[$tid]);
  		}
  		return self::$terms[$tid];
  	}
    private static function colorAlter(&$term){
        if(!empty($term->color) && $term->color == '#ffffff'){
            $term->color = NULL;
        }
    }
  	public function delete($tid){
  		\Drupal::database()->delete('basket_terms')
  					->condition('id', $tid)
  					->execute();
  	}
    public function getOptions($type){
        $options = [];
        foreach (self::tree($type) as $term){
            $options[$term->id] = self::$Basket->Translate()->t($term->name);
        }
        return $options;
    }
    public static function setDefaultNewOrder($tid){
        $term = self::load($tid);
        if(!empty($term)){
            \Drupal::database()->update('basket_terms')
                        ->fields([
                            'default'       => NULL
                        ])
                        ->condition('type', $term->type)
                        ->execute();
            \Drupal::database()->update('basket_terms')
                        ->fields([
                            'default'       => 1
                        ])
                        ->condition('id', $term->id)
                        ->execute();
        }
    }
    public static function getDefaultNewOrder($type = NULL){
      $def = \Drupal::database()->select('basket_terms', 't')
                          ->fields('t', ['id'])
                          ->condition('t.type', $type)
                          ->condition('t.default', 1)
                          ->execute()->fetchField();
      return !empty($def) ? $def : NULL;
    }
}