<?php


namespace App\Repositories;


use App\Document;
use App\DocumentRevision;
use App\DocumentTemplate;
use App\Http\Controllers\DropzoneController;
use App\Http\Controllers\ProjectTypesController;
use App\Http\Controllers\UploadController;
use App\Repositories\Interfaces\DocumentRelationInterface;
use Illuminate\Support\Facades\Log;
use App\User;

class DocumentBaseRepository
{
    const BASE_PATH = "/files/";

    public $classFolderName;
    public $folderId;

    public $isTemplate;
    protected $templateType;

    public $dropzoneName = "newFiles";

    public $projectType;
    protected $documentRelationObject;

    public function resolveDocuments(User $user, $request){

        $jsonOrderFiles = json_decode($request->get($this->dropzoneName));
        $orderFilesError = false;
        if ($jsonOrderFiles == NULL) {
            Log::error("Fehler beim Hinzufügen von Dokumenten; JSON-Fehler: " . json_last_error_msg());
            $projectTypeFilesError = true;
        }
        else {
            # Dateien lesen, Pfade bestimmen
            $projectTypeFiles = $jsonOrderFiles->files;
            $projectTypeFileSizes = $jsonOrderFiles->fileSizes;

            if(isset($jsonOrderFiles->documentId)) $documentId = $jsonOrderFiles->documentId;

            $counter = 0;
            $draftPath = DropzoneController::DROPZONE_TMP_PATH;


            foreach ($projectTypeFiles as $projectTypeFile) {
                # Entwurfskennzeichen von Datei entfernen
                $filename = substr($projectTypeFile, 4, strlen($projectTypeFile) - 4);

                # Für angezeigten Dateinamen GUID von Datei entfernen
                $prettyFilename = substr($filename, 9, strlen($filename) - 9);

                # Versionsnummer an Datei anhängen
                 $splitFileName = explode(".", $prettyFilename);
                 $fileType = end($splitFileName);



                # Pfad in Tabelle speichern

                if (!isset($documentId)) {
                    $newDocument = new Document();
                    $newDocument->title = $prettyFilename;

                    try {

                        if($this->documentRelationObject != null)
                        {
                            $this->documentRelationObject->documents()->save($newDocument);
                        }

                        $newDocument->save();
                    } catch (\Exception $e) {
                        Log::error("Fehler beim Hinzufügen von Dokumenten in Datenbank: " . $e->getMessage());
                        $projectTypeFilesError = true;
                        return redirect()->back()->withErrors("Fehler beim Hinzufügen von Dokumenten.");
                    }

                }
                else{
                    $newDocument = Document::find($documentId);
                    $this->setDocumentRelationObject($newDocument->attachable);
                }
                $objectPath = $this->classFolderName . "_files/" . $this->classFolderName . "_" . $this->folderId . "/";
                $fullPath = DocumentBaseRepository::BASE_PATH . $objectPath;


                $newDocumentRevision = new DocumentRevision();
                if(isset($documentId)) {
                    $newDocumentRevision->version = $newDocument->latest_revision()->version + 1;
                }
                else
                {
                    $newDocumentRevision->version = 1;
                }
                $prettyFilenameAndVersion = substr($prettyFilename, 0, strlen($prettyFilename) - strlen($fileType) - 1) . "_" . $newDocumentRevision->version . "." . $fileType;

                $newDocumentRevision->document_id = $newDocument->id;
                $newDocumentRevision->path = $objectPath.$prettyFilenameAndVersion;
                $newDocumentRevision->size = $projectTypeFileSizes[$counter];



                $newDocumentRevision->status = "created";


                # Bild in Storage umbenennen
                UploadController::renameFile($projectTypeFile, $prettyFilenameAndVersion, $draftPath, $fullPath);

                if($this->isTemplate && !isset($documentId))
                {
                    $newDocumentTemplate = new DocumentTemplate();
                    if($this->projectType != null) $newDocumentTemplate->project_type_id = $this->projectType->id;
                    $newDocumentTemplate->document_id = $newDocument->id;
                    $newDocumentTemplate->type = $this->templateType;
                }

                # speichern
                try {
                    $newDocumentRevision->save();
                    if(isset($newDocumentTemplate)) $newDocumentTemplate->save();
                } catch (\Exception $e) {
                    Log::error("Fehler beim Hinzufügen von Dokumenten in Datenbank: " . $e->getMessage());
                    $projectTypeFilesError = true;
                    return redirect()->back()->withErrors("Fehler beim Hinzufügen von Dokumenten.");
                }

                $counter++;
            }
        }
    }


    public function addVersion(User $user, $request){

    }


    public function setTemplateType($templateType)
    {
        $this->templateType = $templateType;
    }

    public function setDocumentRelationObject(DocumentRelationInterface $documentRelationObject)
    {
        $this->documentRelationObject = $documentRelationObject;
        if($documentRelationObject != null)
        {
            $classPath = get_class($documentRelationObject);
            $className = explode("\\", $classPath);
            $this->classFolderName = strtolower(end($className));
            $this->folderId = $documentRelationObject->id;
        }
    }

}