<?php

namespace Ignite\Core\Models\Import;

use Illuminate\Support\Facades\Validator;
use Ignite\Core\Entities\Import;
use Ignite\Core\Entities\Participant;
use League\Csv\Reader;
use League\Csv\Statement;

abstract class Importer
{
    /**
     * The required data that must be available in the file.
     *
     * @var array
     */
    protected $required = [];

    /**
     * The list of "known" fields.
     *
     * @var array
     */
    protected $fields = [];

    /**
     * The import record.
     *
     * @var \Ignite\Import\Entities\Import
     */
    protected $record;

    /**
     * A cache of data to be stored when accessing this instance during a single request.
     *
     * @var array
     */
    protected $cache;

    /**
     * The cached headers.
     *
     * @var array
     */
    protected $headers;

    /**
     * Assign the import data record for this import.
     *
     * @param  Import $record
     * @return self
     */
    public function record(Import $record)
    {
        $this->record = $record;

        return $this;
    }

    /**
     * The total number of records to be imported.
     *
     * @return int
     */
    public function count() : int
    {
        try {
            return $this->getCount();
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * Display the information text as html while previewing the data.
     *
     * @return string
     */
    public function html() : string
    {
        return '';
    }

    /**
     * Preview a single record at the given offset.
     *
     * @param  int $offset
     * @return array
     * @throws \League\Csv\Exception
     */
    public function preview($offset = 1) : array
    {
        $data = $this->getByOffset($offset);

        if (empty($data)) {
            throw new \League\Csv\Exception("Record not found at line $offset");
        }

        return array_combine(
            $this->getHeaders(),
            $data
        );
    }

    /**
     * Process the file and return the iterator.
     *
     * @return iterable
     * @throws \League\Csv\Exception
     */
    public function process(): iterable
    {
        return $this->getRecords();
    }

    /**
     * Return the column header in the csv file to use in order to identify the user.
     *
     * @return string
     */
    abstract protected function getUserIdentifier();

    /**
     * Create a new reader instance from the import file data.
     *
     * @return \League\Csv\Reader
     */
    protected function createFromData()
    {
        return Reader::createFromString($this->record->getFileData());
    }

    /**
     * Create a new reader instance from the import file as a stream resource.
     *
     * @return \League\Csv\Reader
     */
    protected function createFromStream()
    {
        return Reader::createFromStream($this->record->getFileStream());
    }

    /**
     * Create a new reader instance from the import file as a stream resource.
     *
     * @return \League\Csv\AbstractCsv
     */
    protected function createFromPath()
    {
        return Reader::createFromPath($this->record->getFilePath());
    }

    /**
     * Create an instance of a Statement object.
     *
     * @return Statement
     */
    protected function createStatementInstance()
    {
        return new Statement();
    }

    /**
     * Create a new instance the validator.
     *
     * @param  array $data
     * @param  array $rules
     * @param  array $messages
     * @param  array $attributes
     * @return \Illuminate\Validation\Validator
     */
    protected function createValidatorInstance(array $data, array $rules, array $messages = [], array $attributes = [])
    {
        return Validator::make($data, $rules, $messages, $attributes);
    }

    /**
     * Get all of the data rows.
     *
     * @return \League\Csv\Reader
     * @throws \League\Csv\Exception
     */
    protected function getData()
    {
        return $this->createFromStream()->setHeaderOffset(0);
    }

    /**
     * Count the number of records in the data file.
     *
     * @return int
     * @throws \League\Csv\Exception
     */
    protected function getCount()
    {
        return $this->getData()->count();
    }

    /**
     * Fetch one line from the file by offset.
     *
     * @param  int $offset
     * @return array
     * @throws \League\Csv\Exception
     */
    protected function getByOffset($offset)
    {
        return $this->getData()->fetchOne((int) $offset - 1);
    }

    /**
     * Fetch all records.
     *
     * @return \Iterator
     * @throws \League\Csv\Exception
     */
    protected function getRecords()
    {
        return $this->getData()->getRecords($this->getHeaders());
    }

    /**
     * Chunk groups of records records.
     *
     * @param  $length
     * @return \Iterator
     * @throws \League\Csv\Exception
     */
    protected function chunkRecords($length)
    {
        return $this->getData()->chunk($length);
    }

    /**
     * Get the first line from the csv file as the headers.
     *
     * @return array
     * @throws \League\Csv\Exception
     */
    protected function fetchHeaders()
    {
        return $this->createStatementInstance()
            ->offset(0)
            ->limit(1)
            ->process($this->createFromStream())
            ->fetchOne();
    }

    /**
     * Attempt to map the correct fields from the provided headers.
     *
     * @return array
     * @throws \League\Csv\Exception
     */
    public function getHeaders() : array
    {
        if (is_null($this->headers)) {
            $this->headers = array_map(function ($header) {
                return $this->getHeader($header);
            }, $this->fetchHeaders());
        }

        return $this->headers;
    }

    /**
     * Get a single header, if the configured field header matches, return immediately.
     * Otherwise, try to find a configured synonym for the header. Else, return the original header.
     *
     * @param  string $header
     * @return string
     */
    protected function getHeader($header)
    {
        foreach ($this->fields as $field => $synonyms) {
            if (strtolower($header) === strtolower($field)) {
                return $field;
            }
            if ($this->matchSynonyms($header, $synonyms)) {
                return $field;
            }
        }

        return $header;
    }

    /**
     * Attempt to match the header against a list of synonyms.
     *
     * @param  string $header
     * @param  array  $synonyms
     * @return bool
     */
    protected function matchSynonyms($header, $synonyms)
    {
        if (empty($synonyms)) {
            return false;
        }

        $matches = array_filter($synonyms, function ($synonym) use ($header) {
            $transformed = snake_case(str_replace('-', '', $synonym));
            return (strtolower($header) === $transformed);
        });

        return ! empty($matches);
    }

    /**
     * Cache the users in the system as key => value pairs.
     *
     * @todo   Possible that we should extract an `ImportingUserCache` class to encapsulate this or perhaps use a decorator.
     * @param  string $column
     * @param  string $key
     * @return array
     * @throws \League\Csv\Exception
     */
    protected function cacheUsers($column = 'user_id', $key = 'email')
    {
        if (! isset($this->cache['users']) || empty($this->cache['users'])) {
            $keys = $this->getHeaders();

            $lines = $this->createStatementInstance()->offset(1)->process($this->createFromStream(), $keys);
            $userColumn = array_search($column, $keys);

            if (false === $userColumn) {
                throw new \League\Csv\Exception('Unable to locate a header to find the user.');
            }

            $users = $this->preProcessCacheableUsers(iterator_to_array($lines->fetchColumn($userColumn)));
            $users = array_keys(array_flip($users));
            $users = $this->postProcessCacheableUsers($users);

            $this->cache['users'] = $this->getCacheableUsers($key, $users);
        }

        return $this->cache['users'];
    }

    /**
     * Pre process the users lookup before it gets cached.
     *
     * @param  array $users
     * @return array
     */
    protected function preProcessCacheableUsers($users)
    {
        return $users;
    }

    /**
     * Post process the users lookup before it gets cached.
     *
     * @param  array $users
     * @return array
     */
    protected function postProcessCacheableUsers($users)
    {
        return $users;
    }

    /**
     * Fetch the cacheable users from the database.
     *
     * @param  string $key
     * @param  array  $users
     * @return array
     */
    protected function getCacheableUsers($key, $users)
    {
        return Participant::whereIn($key, $users)->get()
            ->keyBy($key)
            ->map(function ($user) {
                return $user->getKey();
            })
            ->toArray();
    }

    /**
     * Attempt to transform a date for storage.
     *
     * @param  array  $line
     * @param  string $field
     * @param  string $format
     * @return string
     */
    protected function transformDate($line, $field, $format = 'Y-m-d H:i:s')
    {
        if (! isset($line[$field]) || empty($line[$field])) {
            return now()->format($format);
        }

        $date = date($format, strtotime($line[$field]));

        if (! $date) {
            throw new \DomainException(sprintf(
                'Unable to import field `%s` because `$attempt` is not a valid date.',
                $field,
                $line[$field]
            ));
        }

        return $date;
    }

    /**
     * Transform the user identifier to ID but throw an exception with an unknown user.
     *
     * @param  array  $line
     * @param  string $key
     * @return int|null
     */
    protected function transformUser($line, $key)
    {
        if (! array_key_exists($key, $line)) {
            throw new \DomainException("Unable to locate the header with name: $key");
        }

        $users = $this->cache['users'];
        if (! array_key_exists($line[$key], $users)) {
            throw new \DomainException("Participant with identifier `${line[$key]}` is not enrolled");
        }

        return $users[$line[$key]];
    }
}
