<?php 

namespace Teknisa\Libs\Util\XLS;

use IReadFilter;

class Filter implements IReadFilter {
    private $startRow; //null to read all
    private $endRow; //null to read all
    private $columns = array(); 
    private $worksheetNames; //null to read all
    private $worksheetNamesCaseSensitive; 

    /**  Get the list of rows, columns and worsheetNames to read  */ 
    public function __construct($startRow = null, $endRow = null, $columns = null, $worksheetNames = null) { 
        $this->startRow = $startRow; 
        $this->endRow   = $endRow; 
        $this->columns  = $columns; 
        $this->worksheetNames  = $worksheetNames; 
        $this->worksheetNamesCaseSensitive = true;
    } 
    
    //Verify if the row is in interval
    private function inRowInterval($row){
        return (($this->startRow == null || $row >= $this->startRow) && 
                ($this->startRow == null || $row <= $this->endRow));
    }
    
    //WorksheetName if the row is in the List
    private function inWorksheetNameList($worksheetName){
        if($this->worksheetNames == null){
            return true;
        }
        if($this->worksheetNamesCaseSensitive){
            return in_array($worksheetName, $this->worksheetNames);
        }
        else{
            return preg_grep( '/'.$worksheetName.'/i' , $this->worksheetNames);
        }
    }
    
    //Column if the row is in the List
    private function inColumnsList($column){
        if($this->columns == null){
            return true;
        }
        return in_array($column, $this->columns);
    }
    
    public function readCell($column, $row, $worksheetName = '') { 
        //  Only read the rows, columns and worsheetNames that were configured 
        return (self::inWorksheetNameList($worksheetName) && 
                self::inRowInterval($row) && self::inColumnsList($column));
    }
    
    public function setColumns($columns){
        $this->columns = $columns; 
    }
    
    public function setEndRow($endRow){
        $this->endRow = $endRow; 
    }
    
    public function setStartRow($startRow){
        $this->startRow = $startRow; 
    }

    public function setWorksheetNames($worksheetNames){
        $this->worksheetNames = $worksheetNames; 
    }
        
    public function setWorksheetNamesCaseSensitive($worksheetNamesCaseSensitive){
        $this->worksheetNamesCaseSensitive = $worksheetNamesCaseSensitive; 
    }
    
} 