<?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 ModalFormPatchFile extends Component
{
    public $openModalFormPatchFile = false;
    public $patchFileId, $patchId, $patchFile, $dbCode, $fileName, $commit, $comparisonResult, $diffResult, $message;
    public $preImpHeader;
    public $isOpenFormPatchFile = false;

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

    public function openModalFormPatchFile($patchFileId = null, $patchId = null)
    {

        $this->patchFileId = $patchFileId;
        $this->patchId = $patchId;
        if (isset($patchFileId) && $patchFileId !== '') {
            $patchFile = TabPatchFile::where('fid', $this->patchFileId)->first();
           
            $this->patchFile = $patchFile->file_name;
            $this->dbCode = base64_decode($patchFile->file_data);
            $this->dbCode = (iconv('TIS-620', 'UTF-8', $this->dbCode));
        }else{
            $this->patchFile = '';
            $this->dbCode = '';
        }


        $this->isOpenFormPatchFile = true;
    }


    public function closeModal()
    {
        $this->isOpenFormPatchFile = 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->isOpenFormPatchFile = false;
    }
    public function render()
    {
        return view('livewire.pages.patch.modal-form-patch-file');
    }

    public function saveCode($dbCode, $fileName)
    {
        $dbCode = (iconv('UTF-8', 'TIS-620', $dbCode));
        if (isset($this->patchFileId) && $this->patchFileId !== '') {
            $pathFile = TabPatchFile::where("fid", $this->patchFileId)->first();
            $pathFile->file_name = $fileName;
            $pathFile->file_data = base64_encode($dbCode);
            $pathFile->save();
        } else {
            $filepath = new TabPatchFile;
            $filepath->ptid = $this->patchId;
            $filepath->file_name = $fileName;
            $filepath->file_data = base64_encode($dbCode);
            $filepath->save();
        }

        $this->isOpenFormPatchFile = false;
        $this->emit('reloadComponent',$this->patchId );
    }
}
