<?php

namespace Bongo\Builder\Seeders;

use Bongo\Builder\Facades\DesignFacade;
use Bongo\Builder\Models\BuilderItem;
use Exception;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class DesignSeeder extends Seeder
{
    /**
     * @throws Exception
     */
    public function run(): void
    {
        // This is only run if we have to re-import the content.js plugin file
        if (file_exists(__DIR__.'/designs.js')) {
            $fileData = $this->cleanContentsFile();
            File::put(__DIR__.'/designs.json', $fileData);
        }

        // Make sure we have the designs.json file
        if (! file_exists(__DIR__.'/designs.json')) {
            throw new Exception('File designs.json does not exist to import');
        }

        // Get the json designs from the designs file
        $jsonDesigns = File::get(__DIR__.'/designs.json');
        $jsonDesigns = json_decode($jsonDesigns, true);
        $defaultImage = File::get(public_path('images/default_image.png'));

        // Loop through and create the files
        foreach ($jsonDesigns as $jsonDesign) {
            try {
                // Get the design name from the image preview
                $name = str_replace('preview/', '', $jsonDesign['thumbnail']);
                $name = str_replace('.png', '', $name);

                // Create the directories
                $categories = config('builder.categories');
                foreach ($categories as $category) {
                    $directory = base_path(config('builder.vendor_path').config('builder.design_path')).trim(strtolower(Str::slug($category)));
                    if (! File::exists($directory)) {
                        File::makeDirectory($directory);
                    }
                }

                // Create the design
                $design = new BuilderItem('design');
                $design->setName($name);
                $design->setKey($name);

                // Get the thumbnail
                if (file_exists(__DIR__.'/design/'.$jsonDesign['thumbnail'])) {
                    $design->setThumbnail(File::get(__DIR__.'/design/'.$jsonDesign['thumbnail']));
                } else {
                    $design->setThumbnail($defaultImage);
                }

                // Set the category
                $categories = config('builder.categories');
                if (isset($categories[$jsonDesign['category']])) {
                    $design->setCategory($categories[$jsonDesign['category']]);
                } else {
                    console_print($jsonDesign['category']);
                }

                // Save
                $design->setHtml($jsonDesign['html']);
                $design->save();

            } catch (Exception $e) {
                console_print($e);
                continue;
            }
        }
    }


    private function cleanContentsFile(): array|string
    {
        $fileData = File::get(__DIR__.'/designs.js', true);

        // Replace all return and new line characters
        $fileData = preg_replace("/\r|\n/", '', $fileData);
        $fileData = str_replace('\n', '', $fileData);

        // Remove the js concatenations
        $fileData = str_replace('+', '', $fileData);

        // Replace any javascript tab functions
        $fileData = str_replace('_tabs(1)', '', $fileData);
        $fileData = str_replace('_tabs(2)', '', $fileData);
        $fileData = str_replace('_tabs(3)', '', $fileData);
        $fileData = str_replace('_tabs(4)', '', $fileData);
        $fileData = str_replace('_tabs(5)', '', $fileData);
        $fileData = str_replace('_tabs(6)', '', $fileData);
        $fileData = str_replace('_tabs(7)', '', $fileData);
        $fileData = str_replace('_tabs(8)', '', $fileData);
        $fileData = str_replace('_tabs(9)', '', $fileData);
        $fileData = str_replace('_tabs(10)', '', $fileData);

        // Replace multiple spaces with a single space
        $fileData = preg_replace('/\s+/', ' ', $fileData);
        $fileData = preg_replace('/>\s+</m', '><', $fileData);

        // Escape all the html double quotes
        $fileData = preg_replace_callback('/<([^<>]+)>/', function ($matches) {
            return str_replace('"', '\"', $matches[0]);
        }, $fileData);

        // Escape all the double quotes in the content
        $fileData = preg_replace_callback('/>(.*?)</', function ($matches) {
            return str_replace('"', '', $matches[0]);
        }, $fileData);

        // Make sure the first and last character in the html block have a double quote
        $fileData = preg_replace('/\s+/', ' ', $fileData);
        $fileData = str_replace("'html': '", "'html' : ".'"', $fileData);
        $fileData = str_replace("' }", '" }', $fileData);

        // Strip all incorrect literals
        $fileData = str_replace("'<", '<', $fileData);
        $fileData = str_replace(">'", '>', $fileData);

        // Replace all single quotes with double quotes
        $fileData = str_replace("'", '"', $fileData);
        $fileData = str_replace('// {', '', $fileData);

        // Remove placeholder text
        $fileData = str_replace('"PRODUCT NAME"', '', $fileData);

        // Update the image paths
        $fileData = str_replace('assets/minimalist-blocks/', '/designs/images/', $fileData);
        $fileData = str_replace('[%IMAGE_PATH%]', '/designs/images/', $fileData);

        return $fileData;
    }
}
