<?php

namespace App\Services\SoftwareLicense;

use App\Models\SoftwareLicense\SoftwareLicenseKey;
use App\Repositories\SoftwareLicense\LicenseRepository;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Auth;
use App\Services\SoftwareLicense\LicenseHistoryService;

/**
 * Software License Document Service
 */
class LicenseDocumentService
{

    protected $licenseRepo;
    protected $licenseHistoryService;

    /**
     * Constructor for Software License Service
     *
     * @param object $licenseRepo
     */
    public function __construct(LicenseRepository $licenseRepo, LicenseHistoryService $licenseHistoryService)
    {
        $this->licenseRepo = $licenseRepo;
        $this->licenseHistoryService = $licenseHistoryService;
    }

    /**
     * Save documenst of the license
     */
    public function saveDocuments($fileName, $licenseId)
    {
        $data = [
            'software_license_id' => $licenseId,
            'file_name' => $fileName
        ];

        $this->licenseRepo->saveDocuments($data);
        $description = 'New document ' . $fileName . ' added';

        $this->licenseRepo->addLicenseHistory([
            'software_license_id' => $licenseId,
            'action' => 'document_added',
            'description' => $description,
            'document' => $fileName,
            'user_id' => Auth::id()
        ]);
    }

    /**
     * Save attachments of the license
     */
    public function removeDocumentFromLicense($id)
    {
        try {
            $document = $this->licenseRepo->getDocument($id);
            $path = storage_path('app/public/software-assets/');
            $file = $path . $document->file_name;

            if (File::exists($file)) {
                File::Delete($file);
            }
            $this->licenseRepo->deleteDocument($id);
            $description = 'Document ' . $document->file_name . ' removed';

            $this->licenseRepo->addLicenseHistory([
                'software_license_id' => $document->software_license_id,
                'action' => 'document_removed',
                'description' => $description,
                'document' => $document->file_name,
                'user_id' => Auth::id()
            ]);

            return ['status' => true, 'license_id' => $document->software_license_id];
        } catch (Exception $e) {
            Log::error($e->getMessage());

            return ['status' => false, 'license_id' => $document->software_license_id];
        }
    }

    /**
     * List Software License Documents
     *
     * @param int $licenseId
     */
    public function getLicenseDocuments(int $licenseId)
    {
        $licenseDocuments = $this->licenseRepo->getLicenseDocuments($licenseId);
        $start = request('start');
        $limit = request('length');
        $count = $licenseDocuments->count();

        if ($limit != -1) {
            $licenseDocuments = $licenseDocuments->offset($start)->limit($limit);
        }
        $licenseDocuments = $licenseDocuments->orderBy('created_at', 'desc');
        $licenseDocuments = $licenseDocuments->get();

        return compact('licenseDocuments', 'count');
    }

    /**
     * Set up Software License documents for listing page
     *
     * @param object $licenseDocuments
     * @param mixed $start
     * @param array $data
     *
     * @return array
     */
    public function getLicensesDocumentData(object $licenseDocuments, $start, array $data)
    {
        $parentIndex = $start;

        foreach ($licenseDocuments as $key => $licenseDocument) {
            $parentIndex++;
            $nestedData = $this->getLicensesDocumentNestedData($licenseDocument, $parentIndex);

            $data[] = $nestedData;
        }

        return $data;
    }

    /**
     * Formatting Software License documents for listing page
     *
     * @param object $licenseDocument
     * @param int $index
     *
     * @return array
     */
    public function getLicensesDocumentNestedData(object $licenseDocument, int $index)
    {
        $nestedData['id']         = $index;
        $nestedData['file_name']   = $licenseDocument->file_name;
        $nestedData['date_added'] = $licenseDocument->created_at ? $licenseDocument->created_at : '' ;
        $downloadAction   = "<a href='/software-assets/" . $licenseDocument->id . "/download-document'><i class='icon icon-box-arrow-down'></i></a>";
        $removeAction = "<a style='margin-left:15px;'' class='delete-document' data-id='" . $licenseDocument->id . "' data-toggle='modal' data-target='#deleteLicenseDocumentModal'><i class='icon icon-delete-forever'></i></a>";
        $nestedData['action_download_only'] = $downloadAction;
        $nestedData['action']  = $downloadAction . " " . $removeAction;

        return $nestedData;
    }

    /**
     * get License Document with id
     *
     * @param int $id
     *
     * @return object
     */
    public function getLicenseDocument(int $id)
    {
        return $this->licenseRepo->getLicenseDocument($id);
    }
}
