<?php

namespace App\Http\Livewire\Pages\Patch;

use App\Models\TabPatchFile;
use Livewire\Component;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Jfcherng\Diff\Differ;
use Jfcherng\Diff\DiffHelper;
use Jfcherng\Diff\Factory\RendererFactory;

class ModalEditCode extends Component
{
    public $openModalEditCode = false;
    public $patchFileId, $patchFile, $gitCode, $gitCodeRaw, $dbCode, $commit, $selectedProject, $comparisonResult, $diffResult, $message;
    public $preImpHeader;
    public $isOpenEditCode = false;

    protected $listeners = ['openModalEditCode' , 'deleteSubItem'];

    public function openModalEditCode($patchFileId, $selectedProject)
    {
        $this->selectedProject = $selectedProject;
        $this->patchFileId = $patchFileId;

        $patchFile = TabPatchFile::where('fid', $this->patchFileId)->first();
        $this->patchFile = $patchFile->file_name;
        $this->dbCode = base64_decode($patchFile->file_content); // Adjust accordingly based on your database schema

        $this->gitCodeRaw = $this->getFileContentFromGit($this->patchFile, $this->commit);
        try {
            $this->gitCode = (iconv('TIS-620', 'UTF-8', $this->gitCodeRaw));
        } catch (\Throwable $th) {
            $this->gitCode = "This is image cannot show !";
        }
       
        $this->isOpenEditCode = true;
    }


    public function closeModal()
    {
        $this->isOpenEditCode = false;
    }
    public function updateCode()
    {
    }
    private function getFileContentFromGit($filePath, $commit)
    {
        $token = env('GITLAB_API_TOKEN');

        $client = new Client([
            'base_uri' => 'https://idemo.netbay.co.th/gitlab/api/v4/',
            'headers' => [
                'Authorization' => "Bearer $token",
                'Accept' => 'application/json',
            ],
            'verify' => false,
        ]);

        if (strpos($filePath,  "../SPN/") !== false) {
            $filePath =  str_replace("../SPN/", "SPN/",  $filePath);
        } else if (strpos($filePath,  "../spn/") !== false) {
            $filePath =  str_replace("../spn/", "spn/",  $filePath);
        } else {
            $filePath = str_replace("./", "IE5DEV.shippingnet/", $filePath);
        }


        try {
            $response = $client->get("projects/{$this->selectedProject}/repository/files/" . urlencode($filePath) . "/raw", [
                'query' => ['ref' => $commit]
            ]);
            $statusCode = $response->getStatusCode();
            $content = $response->getBody()->getContents();

            if ($statusCode == 200) {
                return $content;
            } else {
                throw new \Exception("Failed to fetch file. Status code: $statusCode");
            }
        } catch (RequestException $e) {
            throw $e;
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function getDiff($code1, $code2)
    {
        $diffOptions = [
            'context' => 0,
            'ignoreCase' => false,
            'ignoreWhitespace' => true,
        ];

        $rendererOptions = [
            'detailLevel' => 'char',
            'language' => 'eng',
            'lineNumbers' => true,
            'separateBlock' => true,
            'showHeader' => true,
            'spacesToNbsp' => false,
            'outputFormat' => 'inline',
            'mergeThreshold' => 0.8,
            'originalFileName' => 'Original',
            'newFileName' => 'New',
            'cliColorization' => 'none',
        ];

        $differ = new Differ(explode("\n", $code1), explode("\n", $code2), $diffOptions);
        $renderer = RendererFactory::make('Inline', $rendererOptions);
        $result = $renderer->render($differ);
        $result = $this->convertDiffToPrismFormat($result);

        return $result;
    }

    public function compare()
    {

        try {

            // $this->comparisonResult = 'GitLab connection successful.';
            $this->diffResult = $this->getDiff($this->gitCode, $this->dbCode);
            // dd($this->diffResult);
            $this->emit('diffResultUpdated');
        } catch (RequestException $e) {
            $this->comparisonResult = 'Error connecting to GitLab: ' . $e->getMessage();
            $this->gitCode = '';
            $this->gitCodeRaw = '';
        }
    }
    private function convertDiffToPrismFormat($diffHtml)
    {
        $diffHtml = str_replace('<tr data-type="-"', '<tr class="token deleted"', $diffHtml);
        $diffHtml = str_replace('<tr data-type="+"', '<tr class="token inserted"', $diffHtml);
        $diffHtml = str_replace('<td class="old">', '<td class="token deleted">', $diffHtml);
        $diffHtml = str_replace('<td class="new">', '<td class="token inserted">', $diffHtml);
        $diffHtml = str_replace('<th class="sign del">-</th>', '', $diffHtml);
        $diffHtml = str_replace('<th class="sign ins">+</th>', '', $diffHtml);

        return $diffHtml;
    }
    public function showDeleteItemModal($patchFileId)
    {
        $this->emit('showDeleteItemModal' ,$patchFileId); 
    }
    public function deleteSubItem($patchFileId) {
        $pathFile = TabPatchFile::where("fid", $patchFileId)->first();
        $patchId = $pathFile->ptid;

        $pathFile = TabPatchFile::where("fid", $patchFileId)->delete();
        $message = "Deleted File ID : " . json_encode($patchFileId) . " Successfully";
        
        $this->message = $message;
        $this->emit('reloadComponent', $patchId);
        $this->isOpenEditCode = false;
    }
    public function render()
    {
        return view('livewire.pages.patch.modal-edit-code');
    }
}
