<?php

namespace common\components;

use common\models\Card;

class FreeUniqueCardNumberGenerator extends \yii\base\Object {
	public $count;
	public $keyset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	public $length = 6;
	public $cache = [ ];
	public $prefix = "";
	public function generate() {
		if ($this->count == 0) {
			return;
		}
		
		for($i = 0; $i < $this->count; $i ++) {
			
			$unique = false;
			$number = null;
			while ( $unique == false ) {
				$number = Helper::generateRandomString($this->length, $this->keyset);
				$number = $this->prefix . $number;
				$unique = $this->checkCacheUnique ( $number ) && $this->checkDBUniqu ( $number );
			}
			$this->cache [] = $number;
		}
	}
	protected function checkDBUniqu($number) {
		$query = Card::find ();
		Card::addCardNumberCondition ( $query, $number );
		$found = $query->all ();
		$result = count ( $found ) == 0;
		return $result;
	}
	protected function checkCacheUnique($number) {
		return array_search ( $number, $this->cache ) === false;
	}
}