<?php

namespace Ignite\Core\Models\Import;

class File
{
    /**
     * @var string
     */
    protected $type;

    /**
     * @var string
     */
    protected $label;

    /**
     * @var string
     */
    protected $file;

    /**
     * @var string
     */
    protected $disk;

    /**
     * @var string
     */
    protected $log;

    /**
     * Create a new instance from the provided request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  array $allowedTypes
     * @param  string $disk
     * @return static
     */
    public static function fromRequest($request, $allowedTypes = [], $disk = 'local')
    {
        $type = $request->get('type');
        $label = $allowedTypes[$type];
        $folder = 'imports';
        $filename = sprintf('%s-%s',
            snake_case($allowedTypes[$type]),
            now()->format('YmdHis')
        );

        $file = request()->file('file')->storeAs($folder, $filename . '.csv', [
            'disk' => $disk,
            'visibility' => 'public'
        ]);

        $log = $folder . DIRECTORY_SEPARATOR . $filename . '.log';

        return new static($type, $label, $file, $log, $disk);
    }

    /**
     * ImportFile constructor.
     *
     * @param string $type
     * @param $label
     * @param string $file
     * @param string $disk
     */
    public function __construct($type, $label, $file, $log, $disk)
    {
        $this->type = $type;
        $this->file = $file;
        $this->log = $log;
        $this->disk = $disk;
        $this->label = $label;
    }

    /**
     * Cast the object to an array.
     *
     * @return array
     */
    public function toArray()
    {
        return [
            'type' => $this->type,
            'label' => $this->label,
            'file' => $this->file,
            'log' => $this->log,
            'disk' => $this->disk,
        ];
    }

    /**
     * Get the import type.
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Get the import type label.
     *
     * @return string
     */
    public function getLabel()
    {
        return $this->label;
    }

    /**
     * Get the import file path.
     *
     * @return string
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * Get the import log path.
     *
     * @return string
     */
    public function getLog()
    {
        return $this->log;
    }

    /**
     * Get the import file path.
     *
     * @return string
     */
    public function getDisk()
    {
        return $this->disk;
    }
}
