<?php

namespace App\Services\Asn\Shi;

use App\Repositories\Asn\ShiAssetsRepository;
use App\Models\AsnHardwareMapping;
use App\Services\Asn\AbstractAsnMappingService;
use Exception;


class ShiHardwareMappingService extends AbstractAsnMappingService
{
    protected $repository;
    /**
     * ShiHardwareMappingService Constructor
     *
     * @param ShiAssetsRepository $repository
     */
    public function __construct(ShiAssetsRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * Get SHI mapping data
     *
     * @return Eloquent
     */
    public function getAsnMappingData()
    {
        return $repository = $this->repository->getHardwareMappingData()->get();
    }

    /**
     * Filter data
     *
     * @return Eloquent
     */
    public function filter()
    {
        $hardwareMappingData = $this->repository->getHardwareMappingData();

        $hardwareMappingData = $this->repository->filterHardwareMapping($hardwareMappingData, request('make_and_model'), request('technical_spec'), request('searchText'));

        return $hardwareMappingData->get();
    }

    /**
     * Bulk upload
     */
    public function bulkUpload()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $extension   = strtolower(request()->file('bulk_upload_asn_hardware_mapping')->getClientOriginalExtension());
        $path        = request()->file('bulk_upload_asn_hardware_mapping')->storeAs('public/shi_mapping_bulk_upload', 'shi-hardware-mapping-' . date('Ymdhis') . '.' . $extension);

        $path        = storage_path('app/' . $path);
        $message     = 'Bulk mapping successful.';
        $headerMap = Config('bulk-upload.asnHardwareMappingData');
        $checkHeader =  $this->checkHeader($path, $headerMap);
        if ($checkHeader) {
            $errors = 'Upload file do not match the template';

            return compact('errors');
        }

        $errors =  $this->importHardwareMappingData($path, 'shi');
        if ($errors) {
            $message = 'Mapping completed with errors';
        }

        return compact('message', 'errors');
    }
}
