<?php

namespace App\Services\Asn\Insight;

use App\Repositories\Asn\InsightAssetsRepository;
use App\Models\AsnHardwareMapping;
use App\Models\AssetStatus;
use App\Services\Asn\AbstractAsnMappingService;
use Exception;
use Illuminate\Support\Facades\Validator;

class InsightHardwareMappingService extends AbstractAsnMappingService
{
    /**
     * @var $repository
     */
    protected $repository;

    /**
     * insightHardwareMappingService Constructor
     *
     * @param InsightAssetsRepository $repository
     */
    public function __construct(InsightAssetsRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * Get insight mapping data
     *
     * @return Eloquent
     */
    public function getInsightMappingData()
    {
        return $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();
    }

    /**
     * Store mapping to system
     *
     * @return void
     */
    public function store()
    {
        AsnHardwareMapping::Create([
            'provider' => 'insight',
            'make_and_model_id' => request('make_and_model'),
            'technical_spec_id' => request('technical_spec'),
            'part_no' => request('description'),

        ]);

        if (request('sync_now') == 1) {
            $assetStatus = AssetStatus::whereIn('slug', ['insight_in_transit'])->pluck('id');
            $this->individualHardwarePartResync($assetStatus, request('description'), request('make_and_model'), request('technical_spec'));
        }

        return true;
    }

    /**
     * Bulk upload
     */
    public function bulkUpload()
    {
        $extension   = strtolower(request()->file('bulk_upload_insight_hardware_mapping')->getClientOriginalExtension());
        $path        = request()->file('bulk_upload_insight_hardware_mapping')->storeAs('public/insight_mapping_bulk_upload', 'insight-hardware-mapping-' . date('m-d-y') . '.' . $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, 'insight');
        if ($errors) {
            $message = 'Mapping completed with errors';
        }

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