<?php

namespace App\Services;

use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Illuminate\Support\Facades\Storage;

class ImportService{
  public $reader;
  public $writer;

  public function read($filePath)
  {
    $this->reader = ReaderEntityFactory::createReaderFromFile($filePath);
    $this->reader->open($filePath);

    return $this;
  }

  public function readRow()
  {
    $row = $this->reader->getNextRow();
    return $row;
  }

  public function sheetsIterator()
  {
    return $this->reader->getSheetIterator();
  }

  public function write($filePath, $format = 'xsls')
  {
    switch ($format) {
      case 'xsls':
        $this->writer = WriterEntityFactory::createXLSXWriter();
        break;
      case 'csv':
        $this->writer = WriterEntityFactory::createCSVWriter();
        break;
      default:
        throw new \Exception('Unknown format');
    }
    $this->writer->openToFile($filePath);
    $this->format = $format;

    return $this;
  }

  public function makeCells($array_row_data) 
  {
      $cells = [];
      foreach ($array_row_data as $cellValue) {
          $cells[] = WriterEntityFactory::createCell($cellValue);
      }

      return $cells;
  }

  public function makeRow($array)
  {
    return WriterEntityFactory::createRow($this->makeCells($array));
  }

  public function addArrayToRow($array, $sheetName = null)
  {
      // Switch to the correct Sheet Before Write
      if ($sheetName) {
          $currentSheet = $this->writer->getCurrentSheet();
          if ($sheetName != $currentSheet->getName()) {
              $sheets = $this->writer->getSheets();
              foreach ($sheets as $sheet) {
                  if ($sheet->getName() == $sheetName) {
                      $this->writer->setCurrentSheet($sheet); // Set the correct sheet
                      break;
                  }
              }
          }
      }
      $newRow = $this->makeRow($array);
      $this->writer->addRow($newRow);
      return $this;
  }

}
