<?php


class MySQL_Database_Handler
{
    private static $instance = false;
    private $conn = false;


    private function __construct()
    {
        error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
    }

    public static function getInstance()
    {
        if (self::$instance === false) {
            self::$instance = new MySQL_Database_Handler;
        }
        return self::$instance;
    }

    public function get_Senzors_From_Vcelstvo($vcelstvo_id, $date_start, $date_end)
    {
        if($date_start==null and $date_end==null)
        {
            $sql = "select distinct senzor_id ,vcelstvo_id,velicina_id  from thesis where vcelstvo_id= $vcelstvo_id";
        }
        else{
            $sql = "select distinct senzor_id ,vcelstvo_id,velicina_id  from thesis
                    where vcelstvo_id= $vcelstvo_id  and cas>='$date_start' and cas<='$date_end'";
        }
        return $this->open_Con()->query($sql);
    }

   private function open_Con()
    {
        if ($this->conn == false) {
            $file_Path='C:\xampp\Pump_config.ini';
            if(!file_exists($file_Path)){
                throw new Exception('Neexistující soubor Pump_config.ini ');
            }else{
                $config = parse_ini_file($file_Path);
                $this->conn=mysqli_connect($config['database'],$config['username'],$config['password'],$config['dbname']);
                if ($this->conn==false){
                    throw new Exception('Přihlášení do databáze se nezdařilo(zkontrolujte Pump_config.ini) a zkontrolujte přístupnost serveru');
                }

            }
        }
        return $this->conn;
    }

    public function close_Con()
    {
        if ($this->conn != false) {
            $this->conn-> close();
            $this->conn = false;
        }

    }





    public function get_Data_From_Senzor($vcelstvo_id, $senzor_id,$velicina_id ,$date_start, $date_end)
    {

        if ($velicina_id==1){ //kg
            $sql = "select cas, hodnota, stanoviste_id from thesis 
                    where senzor_id=$senzor_id and vcelstvo_id=$vcelstvo_id and hodnota >0";
        }
        elseif($velicina_id==2){//celsius
            $sql = "select cas, hodnota, stanoviste_id from thesis 
                    where senzor_id=$senzor_id and vcelstvo_id=$vcelstvo_id and (hodnota >-40 and hodnota <70)";
        }
        elseif ($velicina_id==3){//percent
            $sql = "select cas, hodnota, stanoviste_id from thesis
                    where senzor_id=$senzor_id and vcelstvo_id=$vcelstvo_id  and (hodnota >10 and hodnota <100)";
        }
        else{
            return null;
        }

        if($date_start!=null and $date_end!=null)
        {
            $sql.=" and cas>='$date_start' and cas<='$date_end'";
        }
        return $this->open_Con()->query($sql);
    }



}