<?php

namespace App\Http\Livewire;

use Livewire\Component;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Jfcherng\Diff\Differ;
use Jfcherng\Diff\DiffHelper;
use Jfcherng\Diff\Factory\RendererFactory;
use Jfcherng\Diff\Renderer\RendererConstant;
use Jfcherng\Diff\Renderer\Html\Inline;

class CodeComparer extends Component
{
    public $code;
    public $gitCode;
    public $gitCodeRaw;
    public $comparisonResult;
    public $diffResult;

    public function mount()
    {
        $this->code = '';
        $this->gitCodeRaw = $this->getCodeFromGit();
        $this->gitCode = (iconv('TIS-620', 'UTF-8', $this->gitCodeRaw));
        $this->diffResult = '';
    }

    public function compare()
    {

        try {
            $this->gitCodeRaw = $this->getCodeFromGit();
            $this->gitCode = (iconv('TIS-620', 'UTF-8', $this->gitCodeRaw));
            $this->comparisonResult = 'GitLab connection successful.';
            $this->diffResult = $this->getDiff($this->gitCode, $this->code);
            // dd($this->diffResult);
            $this->emit('diffResultUpdated');
        } catch (RequestException $e) {
            $this->comparisonResult = 'Error connecting to GitLab: ' . $e->getMessage();
            $this->gitCode = '';
            $this->gitCodeRaw = '';
        }
    }

    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;
    }

    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 getCodeFromGit()
    {
        $projectId = 60; // ใช้ Project ID ที่ถูกต้อง
        $filePath = 'IE5DEV.shippingnet/USERFUNC.inc'; // เส้นทางไฟล์ที่ถูกต้อง
        $branch = 'master'; // หรือ branch ที่คุณต้องการ
        $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,
        ]);

        try {
            $response = $client->get("projects/$projectId/repository/files/" . urlencode($filePath) . "/raw", [
                'query' => ['ref' => $branch]
            ]);
            $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) {
            $this->comparisonResult = 'RequestException: ' . $e->getMessage();
            throw $e;
        } catch (\Exception $e) {
            $this->comparisonResult = 'Exception: ' . $e->getMessage();
            throw $e;
        }
    }

    public function render()
    {
        //asdsda
        
        return view('livewire.code-comparer');
    }
}
