<?php
namespace Models;

class Piot extends \DB\SQL\Mapper{
	public $db, $f3, $sets, $piot, $logs, $messages;

	public function __construct($db, $f3) {
		$this->f3=$f3;
		$this->db=$db;
		$s=new \Models\Settings($this->f3, $this->db);
		$this->sets=$s->get_base();
		if($this->sets['piot_driver']!='' && file_exists($this->sets['piot_driver'].'/server.php')) {
			$class=explode('/', $this->sets['piot_driver']);
			$class=array_reverse($class);
			$model='\Models\\'.$class[0];
			if(!class_exists($model, false)) {
				require_once($this->sets['piot_driver'].'/server.php');
			}
			$config=$s->get_driver_config($this->sets['piot_driver'], 'piot');
			$config=$config['config'];
			$this->piot=new $model($f3, $this->sets, $config);
		}
		else {
			$this->sets['piot_driver']='';
		}
		$this->logs=$this->f3->get('logs_model');
		$this->messages=new \Models\Messages;
	}

	function check_mark($line, $mark) {
		if($this->sets['piot_driver']=='') {
			$res=array(
				'success'=>false,
				'txt'=>$txt
			);
		}
		else {
			$res=$this->piot->check_mark($line, $mark);
		}
		if(isset($res['success']) && $res['success']==false) {
			$txt=$this->messages->message($res['txt']??'piot_off')['txt'];
			$this->logs->save_log($txt, 'error');
			return array(
				'success'=>false,
				'txt'=>$txt
			);
		}
		return $res;
	}

	// Список драйверов
	function get_drivers() {
		$drivers=array();
		$piot_dir=$this->f3->get('piot_dir');
		$dirs=scandir($piot_dir); // Ищем все драйвера
		if($dirs) {
			foreach ($dirs as $d) {
				$folder=$piot_dir.$d;
				$file=$folder.'/driver.config';
				if(is_dir($folder) && file_exists($file)) {
					$config=parse_ini_file($file);
					if($config) {
						$drivers[$folder]=array(
							'title'=>$config['ServerName'],
							'method_title'=>$config['PayName'],
							'path'=>$folder
						);
					}
				}
			}

			foreach ($dirs as $d) {
				$folder=$piot_dir.$d;
				$file=$folder.'/server.config';
				if(is_dir($folder) && file_exists($file)) {
					$config=parse_ini_file($file);
					if($config) {
						$drivers[$folder]=array(
							'title'=>$config['ServerName'],
							'method_title'=>$config['PayName'],
							'path'=>$folder
						);
					}
				}
			}
		}
		return $drivers;
	}
}