<?php


class SupsysticTablesPro_Importer_Model_Importer extends SupsysticTables_Core_BaseModel
{
    /**
     * Imports the file content to the table.
     * @param int $id Table id
     * @param array $file File info
     * @throws \SupsysticTablesPro_Importer_Exception_UnsupportedType
     * @throws \SupsysticTablesPro_Importer_Exception_Upload
     */
    public function import($id, array $file, $settings)
    {
        if ($file['error'] !== UPLOAD_ERR_OK) {
            switch ($file['error']) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    $message = $this->environment->translate(
                        'The uploaded file exceeds the max size of uploaded files.'
                    );
                    break;

                case UPLOAD_ERR_PARTIAL:
                    $message = $this->environment->translate(
                        'The uploaded file was only partially uploaded.'
                    );
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $message = $this->environment->translate(
                        'No file was uploaded.'
                    );
                    break;
                case UPLOAD_ERR_NO_TMP_DIR:
                    $message = $this->environment->translate(
                        'Missing a temporary folder.'
                    );
                    break;
                case UPLOAD_ERR_CANT_WRITE:
                    $message = $this->environment->translate(
                        'Failed to write file to disk.'
                    );
                    break;
                default:
                    $message = $this->environment->translate(
                        'Unexpected error.'
                    );
            }

            throw new SupsysticTablesPro_Importer_Exception_Upload($message);
        }

        try {
            $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
			$remove = empty($settings['append_data']);
			$raw = isset($settings['raw_data']) && $settings['raw_data'];
			$visibleData = isset($settings['visible_data']) && $settings['visible_data'];
            $importer = $this->createImporter($extension);
            $importer->setSettings(array(
                'id' => $id,
                'remove' => $remove,
                'raw' => $raw,
                'visibleData' => $visibleData,
                'model' => $this
                ));
            $data = $importer->import($file['tmp_name'], $extension);
            $this->updateTableData($id, $data, $remove);
        } catch (InvalidArgumentException $e) {
            throw new SupsysticTablesPro_Importer_Exception_UnsupportedType(
                $e->getMessage()
            );
        } catch (PHPExcel_Exception $e) {
			throw new SupsysticTablesPro_Importer_Exception_UnsupportedType(
				$e->getMessage()
			);
		}
    }

    public function importSpreadheets($id, $settings)
    {
        preg_match('/([\w-]{25,}).+#gid=(\d+)/', $settings['url'], $matches);
        if (empty($matches)) {
            throw new SupsysticTablesPro_Importer_Exception('Wrong spreadsheet id or url');
        }
        $spreadsheetId = $matches[1];
        $sheetId = $matches[2];
        $url = "https://docs.google.com/spreadsheets/d/$spreadsheetId/export?format=xlsx&gid=$sheetId";
		$response = wp_remote_get($url);
		if (is_wp_error($response)) {
			throw new SupsysticTablesPro_Importer_Exception($response->get_error_message());
		}
		$contentType = wp_remote_retrieve_header($response, 'content-type');
		if (strpos($contentType, 'application') === false) {
			throw new SupsysticTablesPro_Importer_Exception('please, check the sharing settings of your spreadsheet. It must be accessed to edit for everyone who has link.');
		}
		$file = wp_remote_retrieve_body($response);
		if (empty($file)) {
			throw new SupsysticTablesPro_Importer_Exception(error_get_last());
		}
        try {
			$importer = new SupsysticTablesPro_Importer_Type_Xlsx();
            $temp = tempnam(sys_get_temp_dir(), 'spreadsheet');
            $handler = fopen($temp, 'w+');
            fwrite($handler, $file);
            fclose($handler);

			try {
                $importer->setSettings(array(
                    'id' => $id,
                    'remove' => (isset($settings['append_data']) && $settings['append_data'] ? false : true),
                    'raw' => (isset($settings['raw_data']) && $settings['raw_data'] ? true : false),
                    'model' => $this
                ));
				$data = @$importer->import($temp, 'xlsx');
				$this->updateTableData($id, $data, $data['remove']);
				unlink($temp);
			} catch (PHPExcel_Exception $e) {
				$message = strtolower($e->getMessage());

				throw new SupsysticTablesPro_Importer_Exception(
					"possible reason - $message Also, please, check the sharing settings of your spreadsheet: it must be accessed to edit for everyone who has link."
				);
			}
        } catch (InvalidArgumentException $e) {
            throw new SupsysticTablesPro_Importer_Exception_UnsupportedType(
                $e->getMessage()
            );
        }
    }

    protected function createImporter($type)
    {
        $importer = null;

        switch (strtolower($type)) {
            case 'csv':
                $importer = new SupsysticTablesPro_Importer_Type_Csv();
                break;
            case 'xls':
            case 'xlsx':
                $importer = new SupsysticTablesPro_Importer_Type_Xlsx();
                break;
            default:
                throw new InvalidArgumentException(
                    sprintf(
                        $this->environment->translate(
                            'Unsupported file type "%s".'
                        ),
                        $type
                    )
                );
        }

        return $importer;
    }

    public function updateTableData($id, $data, $remove = false)
    {
		/** @var SupsysticTables_Core_Module $core */
        $core = $this->environment->getModule('core');
        /** @var SupsysticTables_Tables_Model_Tables $tables */
        $tables = $core->getModelsFactory()->get('tables');

		// Set table rows
		$tables->setRows($id, (array) $data['rows'], $remove);

        if(isset($data['removeRows']) && $data['removeRows'] > 0) {
            $tables->removeLastRows($id, $data['removeRows']);
        }
        if(isset($data['lastColumn']) && $data['lastColumn'] >= 0) {
            $tables->removeLastColumns($id, $data['lastColumn']);
        }

		// Set table meta
        if(isset($data['meta'])) {
            $meta = $tables->getMeta($id);
            if(isset($data['meta']['columnsWidth'])) {
                $meta['columnsWidth'] = $data['meta']['columnsWidth'];
            }

            if(isset($data['meta']['mergedCells'])) {
                $meta['mergedCells'] = $data['meta']['mergedCells'];
            }
            $tables->setMeta($id, $meta);
        }

		if(isset($data['conditions'])) {
			$conditions = $core->getModelsFactory()->get('conditions', 'tables');
			$conditions->removeConditions($id);
			$conditions->setConditions($id, $data['conditions']);
		}
    }
}

