<?php

namespace Teknisa\Libs\Util\XLS;

use Teknisa\Libs\Util\XLS\Filter;
use PhpOffice\PhpSpreadsheet\IOFactory;

class FileLoader { // Accepts xls, slsx e ods formats
    
    //It creates a PHPExcel object for only reading
    private static function createXlsReader($directory, $sheetsToLoad, $readDataOnly, $readEmptyCells){
        $inputFileType = IOFactory::identify($directory);
        $xlsReader = IOFactory::createReader($inputFileType);
        $xlsReader->setReadEmptyCells($readEmptyCells);
        
        $xlsReader->setReadDataOnly($readDataOnly);
        $xlsReader->setLoadSheetsOnly($sheetsToLoad);
        
        return $xlsReader;
    }
    
    //It stores a file on the server in a temp directory
    private static function createXlsTempDirectory($content, $name){
        $fileName = sys_get_temp_dir(). DIRECTORY_SEPARATOR . $name;
        $file = fopen($fileName , 'w+');
        if(!$file){
            throw new \Exception('XLS_READER_OPEN_ERROR', 500);
        }
        fputs($file, $content);
        return $fileName;
    }
    
    //It decodes a base 64 file
    private  static function decodeFile($encodedFile) {
        $file = base64_decode($encodedFile);
        return $file;
    }

    /*
    * It loads a base 64 spreadsheet file, creates an object with the content of 
    it and returns it;
    */
    public static function loadFromBase64($content, $name, $sheetsToLoad = null, Filter $filter = null, $readDataOnly = false, $readEmptyCells = false){
        $directory = self::createXlsTempDirectory(self::decodeFile($content), $name);
        $xlsReader = self::createXlsReader($directory, $sheetsToLoad, $readDataOnly, $readEmptyCells);
        if($filter != null){
            $xlsReader->setReadFilter($filter);
        }
        $xlsFile  = $xlsReader->load($directory); //returns an object with the content of the file;
        unlink($directory);
        return $xlsFile;
    }
    
}