<?php

namespace App\Http\Controllers\DiscoveryTools\WorkspaceOne;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Responses\ReportJsonResponse;
use App\Models\AssetStatus;
use App\Services\DiscoveryTools\WorkspaceOne\CheckingInNotCreated;
use App\Http\Traits\DiscoveryToolsAssetUpdateTrait;
use App\Models\AirWatch;
use App\Models\IntegrationSyncHistory;

class CheckingInNotCreatedController extends Controller
{
    use DiscoveryToolsAssetUpdateTrait;
    protected $workspaceOneService;

    public function __construct(CheckingInNotCreated $workspaceOneService)
    {
        $this->workspaceOneService = $workspaceOneService;
    }

    /**
     * Devices not created page
     * @return [type]
     */
    public function index()
    {
        $assetStatuses = AssetStatus::orderBy('slug')->get();
        $lastSync = IntegrationSyncHistory::getLastSync(config('integration-sync-histories.chromebook'))->first();
        $lastSyncDate = $lastSync?->created_at;

        return view('discovery-tools.workspace-one.checking-in-not-created', compact('assetStatuses', 'lastSyncDate'));
    }

    /**
     * data to show the devices not created
     * @param Request $request
     *
     * @return [type]
     */
    public function data(Request $request)
    {
        $filteredData = $this->workspaceOneService->data();

        if (!empty($filteredData['assets'])) {
            $data = $this->workspaceOneService->getReportData($filteredData['assets'], request('start'));
        }

        return new ReportJsonResponse($request->input('draw'), $data, $filteredData['count']);
    }

    /**
     * export the report to csv
     * @return [type]
     */
    public function export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $data = [];
        $datas = collect();

        $assetsNotCreated =  $this->workspaceOneService->exportData();
        $requiredColumns = config('discovery-tools-export-columns.workspaceOne.Common');

        $assetsNotCreated->chunk(5000, function ($assetChunks) use ($data, $datas, $requiredColumns) {
            $datas->push($this->workspaceOneService->getReportExportData($assetChunks, 0, $data, $requiredColumns));
        });

        return exportToCsv($datas->toArray(), $requiredColumns);
    }

    /**
     * create asset
     *
     * @return void
     */
    public function create()
    {
        $workspaceOneAsset = AirWatch::find(request('workspace-one-asset-id'));
        $this->CreateAsset($workspaceOneAsset);
        return redirect('/discovery-tools/workspace-one/checking-in-not-created')->with('message', 'Asset created successfully.');
    }
}
