<?php

namespace App\Http\Controllers\DiscoveryTools\JumpCloud;

use App\Http\Controllers\Controller;
use App\Http\Responses\ReportJsonResponse;
use App\Services\DiscoveryTools\JumpCloud\AllJumpCloudService;
use Illuminate\Http\Request;

class AllJumpCloudController extends Controller
{

    protected $allReport;

    public function __construct(AllJumpCloudService $allReport)
    {
        $this->allReport = $allReport;
    }

    /**
     * Showing the 'All JumpCloud' Report
     * @return view
     */
    public function index()
    {
        return view('discovery-tools.jumpcloud.all-report');
    }

    /**
     * Taking the data to the `All JumpCloud` report
     *
     * @param Illuminate\Http\Request $request
     * @return Http\Response
     */
    public function data(Request $request)
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        $filteredData = $this->allReport->data();
        $assets = $filteredData['assets'];


        $start = request('start');
        $data = [];

        if (!empty($assets)) {
            $data = $this->allReport->getReportData($assets, $start, $data);
        }

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


    /**
     * Export the data from the `All JumpCloud` report
     *
     * @return Http\Response
     */
    public function export()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        $data = [];
        $datas = collect();
        $filteredData = $this->allReport->exportData();
        $requiredColumns = config('discovery-tools-export-columns.jumpcloud.Common');

        $filteredData->chunk(5000, function ($filteredDataChunks) use ($data, $datas, $requiredColumns) {
            $datas->push($this->allReport->getReportExportData($filteredDataChunks, $data, $requiredColumns));
        });

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