<?php
namespace Shared;

class DBTorrentToDistribute
{
    private static $tableName="distributedtorrent";

    public static $colId="id";
    public static $colName="name";
    public static $colActive="active";
    public static $collAllInstalled="allInstalled";
    public static $colSomeExtra="someExtra";
    public static $colSomePaused="somePaused";
    public static $colData="data";
    

    public $Id;
    public $Name;
    public $Active;
    public $AllInstalled;
    public $SomeExtra;
    public $Data;
    public $IsDataLoaded;
    public $Groups;

    private $DataChanged;

    public function __construct($dataRow)
    {
        $this->Id=@$dataRow[self::$colId];
        $this->Name=$dataRow[self::$colName];
        $this->Active=$dataRow[self::$colActive]==1;
        $this->AllInstalled=@$dataRow[self::$collAllInstalled]==1;
        $this->SomeExtra=@$dataRow[self::$colSomeExtra]==1;
        $this->SomePaused=@$dataRow[self::$colSomePaused]==1;

        if(isset($dataRow[self::$colData]))
        {
            $this->Data=$dataRow[self::$colData];
            $this->IsDataLoaded=true;
            $this->DataChanged=true;
        }
        $this->Groups = self::getGroups($this->Id);
    }

    public function AddGroupByName($nameToAdd)
    {
        if(trim($nameToAdd)=="")return false;
        $result=\Shared\MySQL::GetMySQL()->where("groupname",$nameToAdd)->get("groups",array("id"));
        if(!$result)// groupa neexistuje - založení nové
        {
            $sql=\Shared\MySQL::GetMySQL()->insert("groups", array("groupname"=>$nameToAdd));
            $result=\Shared\MySQL::GetMySQL()->where("groupname",$nameToAdd)->get("groups",array("id"));
            \Shared\Messages::Information("Group ".$nameToAdd." created.");
        }

        $sql=\Shared\MySQL::GetMySQL()->insert("torrentgroup", array(  
            "idgroup" => $result[0]["id"],
            "idtorrent" => $this->Id)
            ); 
        return $sql;            
    }

    public static function getGroups($torrentid)
    {
        $rows=\Shared\MySQL::GetMySQL()->query("SELECT g.id,g.groupname from torrentgroup tg inner join groups g on g.id=tg.idgroup where tg.idtorrent=?",array("i" => $torrentid));
        $groups=array();
        foreach($rows as $row)
        {
            array_push($groups, $row["groupname"]);
        }

        return $groups;
    }

    public function GetData()
    {
        if( $this->IsDataLoaded)
            return $this->Data;
        else
        {
            $arr=\Shared\MySQL::GetMySQL()->where(self::$colId,$this->Id)->get(self::$tableName,
            array(
                self::$colData));
            $this->Data=$arr[0][self::$colData];
            $this->IsDataLoaded=true;
            return $this->Data;
        }
    }

    public function SetData($data)
    {
        $this->DataChanged=true;
        $this->Data=$data;
    }

    public static function GetTorrentsDistributionList($indexed=true)
    {
        $torrsToDistr=array();
        $torrentRows=self::GetAllTorrentsDistributionFromDB();
        if(!is_array($torrentRows))
            return $torrsToDistr;
        foreach($torrentRows as $key=>$torrRow)
        {
            $nTorToDistr=new DBTorrentToDistribute($torrRow);
            $torrsToDistr[$indexed?$nTorToDistr->Name:$key]=$nTorToDistr;
        }
        return $torrsToDistr;
    }

    public static function GetTorrentDistributionByID($id)
    {
        $torrentRows=\Shared\MySQL::GetMySQL()->where(self::$colId,$id)->get(self::$tableName,self::arrayForSelect());
        if(!is_array($torrentRows) || count($torrentRows)!=1)
            return null;
        return new DBTorrentToDistribute($torrentRows[0]);
    }

    public static function AppendClientsData($rowsToUpdate)
    {
        if(is_array($rowsToUpdate))
        {
            foreach($rowsToUpdate as $key=>$torrRow)
            {
                $rowsToUpdate[$key]=self::intappendClientsData($torrRow);
            }
            return $rowsToUpdate;
        }
        else
        {
            return self::intappendClientsData($rowsToUpdate);
        }
    }

    private static function intappendClientsData($rowToUpdate)
    {
        //var_dump($rowToUpdate);
        $rowToUpdate->Clients= \Watcher\DBTorrent::GetTorrentsWithClientDataByTorrentName($rowToUpdate->Name);
        return $rowToUpdate;
    }



    public function Delete()
    {
        foreach($this->Groups as $group)
        {
            self::RemoveGroup($group);            
        }
        return \Shared\MySQL::GetMySQL()->where(self::$colId,$this->Id)->delete(self::$tableName);
    }
    public function RemoveGroup($groupname)
    {
        $result=\Shared\MySQL::GetMySQL()->where("groupname",$groupname)->get("groups",array("id"));
        $sql=\Shared\MySQL::GetMySQL()->where(array("idgroup"=>$result[0]["id"], "idtorrent"=>$this->Id))->delete("torrentgroup"); 
        return $sql;   
    }

    public static function GetAllTorrentsDistributionFromDB()
    {
        return \Shared\MySQL::GetMySQL()->get(self::$tableName,self::arrayForSelect());
    }

    private static function arrayForSelect()
    {
        return array(
            self::$colId,
            self::$colName,
            self::$colActive,
            self::$collAllInstalled,
            self::$colSomePaused);
    }

    public function SaveProgressData()
    {
        $cols= array(          
            self::$collAllInstalled=>$this->AllInstalled?1:0,
            self::$colSomePaused=>   $this->SomePaused?1:0);
    
            if($this->DataChanged)
                    $arr[self::$colData]= $this->Data;

            $this->updateOrSave($cols);
    }

    public function SaveAllData()
    {
      $cols= array(
        self::$colName =>        $this->Name,
        self::$colActive =>      $this->Active?1:0,
        self::$collAllInstalled=>$this->AllInstalled?1:0,
        self::$colSomePaused=>   $this->SomePaused?1:0);

        if($this->DataChanged)
                $cols[self::$colData]= $this->Data;
        return $this->updateOrSave($cols);
        
    }

    private function updateOrSave($arrayColumnsToSave)
    {
        if($this->Id==null)
        {
           \Shared\MySQL::GetMySQL()->insert(self::$tableName,$arrayColumnsToSave);
           $this->Id=\Shared\MySQL::GetMySQL()->insert_id();
        }
        else
        {
            return \Shared\MySQL::GetMySQL()->where(self::$colId,$this->Id)->update(self::$tableName,$arrayColumnsToSave);
        }
    }

    




}