<?php

namespace App\Http\Controllers\Frontend\Graphics;

use App\Http\Controllers\Controller;

use App\Http\Requests\Backend\Clipart\ManageClipartRequest;
use App\Http\Requests\Backend\Clipart\UpdateClipartRequest;
use App\Models\Auth\User;
use App\Models\Graphics\Clipart;
use App\Models\Graphics\Clipart_colourway;
use App\Models\Tag;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use League\Flysystem\File;
use Madnest\Madzipper\Facades\Madzipper;
use SVG\SVG;


class ClipartController extends Controller
{
    //

    /**
     * Display a listing of the clipart
     * @TODO filtering is good, but later
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // this is what we'll use to filter out paid
//        if (\Auth::user()->isPaid) {
//            if (isset($request['tags'])) {
//                $clipart = Clipart::withTags($request['tags'])->get();
//                // dd($clipart);
//            }else{
//                $clipart = Clipart::free()->get();
//            }
//        }


        if (isset($request['tags'])) {
            if (isset($request['text'])) {
                $clipart = Clipart::withTags($request['tags'])->where('name', 'like', "%{$request['search']}%")
                    ->orWhere('description', 'LIKE', "%{$request['search']}%")
                    ->orWhere('citations', 'LIKE', "%{$request['search']}%")->paginate(20);
            } else {
                $clipart = Clipart::withTags($request['tags'])->paginate(20);
            }
        } else {
            if (isset($request['search'])) {
                $clipart = Clipart::where('name', 'like', "%{$request['search']}%")
                    ->orWhere('description', 'LIKE', "%{$request['search']}%")
                    ->orWhere('citations', 'LIKE', "%{$request['search']}%")->paginate(20);
            } else {

                $clipart = Clipart::paginate(20);
            }
        }
// preload baseline ID
        $clipart->each(function ($item, $key) {
            $item->id_baseline = $item->baseline_id;
        });
        $tags = Tag::all();
        return view('backend.clipart.index')
            ->with('tags', $tags)
            ->with('clipart', $clipart);
    }

    public function create(ManageClipartRequest $request)
    {
        $tags = Tag::all();
        return view('backend.clipart.create')
            ->with('tags', $tags);

    }

    public function show(ManageClipartRequest $request, $id)
    {

        $clipart = Clipart::find($id);
        return view('backend.clipart.show')
            ->with('clipart', $clipart);
    }

    public function displaysvg($id, $colour = null)
    {
        // dd($id);
        $clipart = Clipart::find($id);

        // look for the colourway
        if (!$colour) {
            $colour = 'baseline';
        }
        //     try {
        $data = $clipart->colourways->where('colour_name', '=', $colour)->first()->data ?? Storage::get('/public/questionmark.svg');

        $xml = simplexml_load_string($data);
        //insert title and available colourways
        // get available colourways
        $colourways = $clipart->availableColourwaysNames;
        // get title
        $title = $clipart->name;

        //add a little tag to all elements of the scale layer
        foreach ($xml as $item) {
            if ($item['id'] == 'scale_layer') {
                $this->recurse($item);
            }
        }

        // insert title
        $xml[0]['data-title'] = $clipart->name;
        // insert colourways
        $xml[0]['data-colourways'] = $colourways->implode(',');

        $domxml = dom_import_simplexml($xml);


        $content_typestr = 'image/svg+xml';
        $response = new \Illuminate\Http\Response($domxml->ownerDocument->saveXML($domxml->ownerDocument->documentElement), '200');
        $response->header("Content-Type", $content_typestr);
        return $response;
    }


    /**
     * get a thumbnail
     * @param $id
     * @return \Illuminate\Http\Response
     */

    public function thumb($id, $colour = null)
    {
        // dd($colour);
        $clipart = Clipart::find($id);
        if (!$colour) {
            $colour = 'baseline';
        }
        //     try {
        $data = $clipart->colourways->where('colour_name', '=', $colour)->first()->data ?? Storage::get('/public/questionmark.svg');

        // $data = $clipart->colourways->where('colour_name', '=', $colour)->first()->data ?? Storage::get('/public/questionmark.svg');
        $xml = simplexml_load_string($data);
        $xml[0]['height'] = 200;
        $xml[0]['width'] = 200;
        $domxml = dom_import_simplexml($xml);
        $content_typestr = 'image/svg+xml';
        $response = new \Illuminate\Http\Response($domxml->ownerDocument->saveXML($domxml->ownerDocument->documentElement), '200');
        $response->header("Content-Type", $content_typestr);
        return $response;

    }

    // get the default id for the default colourway for this image id
    public function default_image_id($id)
    {
        $clipart = Clipart::find($id);
        return $clipart->colourways->where('colour_name', '=', 'baseline')->first()->id;
    }


    /**
     * Show the edit view for a clipart
     * @param $id
     *
     * @return mixed
     */
    public function edit($id)
    {
        $clipart = Clipart::find($id);
        $tags = Tag::all();
        return view('backend.clipart.edit')
            ->with('tags', $tags)
            ->with('clipart', $clipart);
    }

    /**
     * updates a clipart entry
     *
     * @param UpdateClipartRequest $request
     * @param Clipart $clipart
     *
     * @return mixed
     * @throws \Throwable
     * @throws \App\Exceptions\GeneralException
     */
    public function update(UpdateClipartRequest $request, $id)
    {
// new clipart entry

        $clipart = Clipart::updateOrCreate(['id' => $id],
            ['name' => $request['name'],
                'description' => $request['description'],
                'citations' => $request['citations'],
                'paid' => $request['paid'],
                'type' => 'svg']
        );

        // tags
        if (isset($request['tags'])) {
            $tags = [];
            foreach ($request['tags'] as $item) {
                if (!(Tag::where('id', $item)->exists())) {
                    $new = Tag::updateOrCreate(['text' => $item]);
                    $tags[] = $new->id;
                } else {
                    $tags[] = $item;
                }
            }
            $clipart->tags()->sync($tags);
        }

        // save actual files
        if ($request->has('baseline')) {
            Clipart_colourway::updateOrcreate(['clipart_id' => $clipart->id, 'colour_name' => 'baseline'], ['data' => file_get_contents($request->file('baseline')), 'colour_name' => 'baseline', 'colour' => '#000000']);
            // make a thumb of the baseline
            $clipart->thumb = SVG::fromFile($request->file('baseline'))->toRasterImage(75, 75);
            $clipart->save();
        }
        if ($request->has('blue')) {
            Clipart_colourway::updateOrcreate(['clipart_id' => $clipart->id, 'colour_name' => 'blue'], ['data' => file_get_contents($request->file('blue')), 'colour_name' => 'blue', 'colour' => '#0000FF']);
        }
        if ($request->has('green')) {
            Clipart_colourway::updateOrcreate(['clipart_id' => $clipart->id, 'colour_name' => 'green'], ['data' => file_get_contents($request->file('green')), 'colour_name' => 'green', 'colour' => '#006400']);
        }
        if ($request->has('grey')) {
            Clipart_colourway::updateOrcreate(['clipart_id' => $clipart->id, 'colour_name' => 'grey'], ['data' => file_get_contents($request->file('grey')), 'colour' => '#A9A9A9']);
        }
        if ($request->has('purple')) {
            Clipart_colourway::updateOrcreate(['clipart_id' => $clipart->id, 'colour_name' => 'purple'], ['data' => file_get_contents($request->file('purple')), 'colour' => '#9400D3']);
        }
        if ($request->has('red')) {
            Clipart_colourway::updateOrcreate(['clipart_id' => $clipart->id, 'colour_name' => 'red'], ['data' => file_get_contents($request->file('red')), 'colour' => '#8B0000']);
        }
        if ($request->has('yellow')) {
            Clipart_colourway::updateOrcreate(['clipart_id' => $clipart->id, 'colour_name' => 'yellow'], ['data' => file_get_contents($request->file('yellow')), 'colour' => '#FFD700']);
        }
        if ($request->has('outline')) {
            Clipart_colourway::updateOrcreate(['clipart_id' => $clipart->id, 'colour_name' => 'outline'], ['data' => file_get_contents($request->file('outline')), 'colour' => '#000000']);
        }

        return redirect()->route('admin.clipart.index')->withFlashSuccess('Clipart updated success!');

    }

    /**
     * UNUSED
     * @param ManageClipartRequestRequest $request
     * @param Clipart $clipart
     *
     * @return mixed
     * @throws \Exception
     */
    public function destroy(ManageClipartRequestRequest $request, Clipart $clipart)
    {
        dd($request);
        return;
    }

    public function delete(Request $request)
    {
        $clipart = Clipart::find($request['id']);
        // clean up the colourways
        //$clipart->colourways->delete();
        // remove clipart
        $clipart->delete();
        return redirect()->route('admin.clipart.index')->withFlashSuccess('Clipart deleted success!');
    }


    public function store(Request $request)
    {
        // new clipart entry
        $clipart = Clipart::create(['owner_id' => auth()->user()->id,
            'name' => $request['name'],
            'description' => $request['description'],
            'citations' => $request['citations'],
            'public' => $request['public'],
            'type' => 'svg',
        ]);

        // tags
        if (isset($request['tags'])) {
            $tags = [];
            foreach ($request['tags'] as $item) {
                if (!(Tag::where('id', $item)->exists())) {
                    $new = Tag::updateOrCreate(['text' => $item]);
                    $tags[] = $new->id;
                } else {
                    $tags[] = $item;
                }
            }
            $clipart->tags()->sync($tags);
        }

        // save actual files
        if ($request->has('baseline')) {
            Clipart_colourway::create(['clipart_id' => $clipart->id, 'data' => file_get_contents($request->file('baseline')), 'colour_name' => 'baseline', 'colour' => '#000000']);
        }
        if ($request->has('blue')) {
            Clipart_colourway::create(['clipart_id' => $clipart->id, 'data' => file_get_contents($request->file('blue')), 'colour_name' => 'blue', 'colour' => '#0000FF']);
        }
        if ($request->has('green')) {
            Clipart_colourway::create(['clipart_id' => $clipart->id, 'data' => file_get_contents($request->file('green')), 'colour_name' => 'green', 'colour' => '#006400']);
        }
        if ($request->has('grey')) {
            Clipart_colourway::create(['clipart_id' => $clipart->id, 'data' => file_get_contents($request->file('grey')), 'colour_name' => 'grey', 'colour' => '#A9A9A9']);
        }
        if ($request->has('purple')) {
            Clipart_colourway::create(['clipart_id' => $clipart->id, 'data' => file_get_contents($request->file('purple')), 'colour_name' => 'purple', 'colour' => '#9400D3']);
        }
        if ($request->has('red')) {
            Clipart_colourway::create(['clipart_id' => $clipart->id, 'data' => file_get_contents($request->file('red')), 'colour_name' => 'red', 'colour' => '#8B0000']);
        }
        if ($request->has('yellow')) {
            Clipart_colourway::create(['clipart_id' => $clipart->id, 'data' => file_get_contents($request->file('yellow')), 'colour_name' => 'yellow', 'colour' => '#FFD700']);
        }
        if ($request->has('outline')) {
            Clipart_colourway::create(['clipart_id' => $clipart->id, 'data' => file_get_contents($request->file('outline')), 'colour_name' => 'outline', 'colour' => '#000000']);
        }

        return redirect()->route('admin.clipart.index')->withFlashSuccess('Clipart created success!');
    }

    /**
     * Return a bunch of cliparts
     * @param Request $request
     * @return mixed
     */
    public function searchByTags(Request $request)
    {
        $perpage = 40;
        $returnVal = [];
        if ($request['tags']) {
            $returnVal['items'] = Clipart::withTags($request['tags'])->skip(($request['page'] - 1) * $perpage)->take(($request['page']) * $perpage)->get()->makeHidden('colourways');
            $returnVal['count'] = Clipart::withTags($request['tags'])->count();
        } else {
            $returnVal['items'] = Clipart::skip(($request['page'] - 1) * $perpage)->take(($request['page']) * $perpage)->get()->makeHidden('colourways');
            $returnVal['count'] = Clipart::count();
        }
        $returnVal['items']->map(function ($clipart) {
            // $board['author'] = $board->user->name;
            $clipart['formattedtags'] = $clipart->tags->pluck('text')->join(', ');
            return $clipart;
        });
        return $returnVal;
    }

    /**
     * Return paginated
     * @param Request $request
     * @return mixed
     */
    public function searchByTagsAndText(Request $request)
    {
        // how many clipart to return by page
        $perpage = 40;
        $returnVal = [];
        if ($request['tags']) {
            if (isset($request['search']) && strlen($request['search']) > 1) {
                $returnVal['items'] = Clipart::with('colourways:id,colour_name')->where('name', 'like', "%{$request['search']}%")->orWhere('description', 'like', "%{$request['search']}%")->withTags($request['tags'])->offset(($request['page']) * $perpage)->limit($perpage)->get();
            } else {
                $returnVal['items'] = Clipart::with('colourways:id,colour_name')->withTags($request['tags'])->offset(($request['page']) * $perpage)->limit($perpage)->get()->makeHidden('colourways');
            }
           // $returnVal['count'] = Clipart::withTags($request['tags'])->count();
        } else {
            if (isset($request['search']) && strlen($request['search']) > 1) {
                $returnVal['items'] = Clipart::with('colourways:id,colour_name')->where('name', 'like', "%{$request['search']}%")->orWhere('description', 'like', "%{$request['search']}%")->offset(($request['page']) * $perpage)->limit($perpage)->get();

            } else {
                $returnVal['items'] = Clipart::with('colourways:id,colour_name')->skip(($request['page'] - 1) * $perpage)->offset(($request['page']) * $perpage)->limit($perpage)->get();//->makeHidden('colourways');
                //$returnVal['items'] = Clipart::skip(($request['page'] - 1) * 50)->take(($request['page']) * $perpage)->get()->makeHidden('colourways');
              //  $returnVal['count'] = Clipart::count();
            }
        }
        $returnVal['items']->map(function ($clipart) {
            // $board['author'] = $board->user->name;
            $clipart['formattedtags'] = $clipart->tags->pluck('text')->join(', ');
            return $clipart;
        });
        return $returnVal;
    }

//    This could take a while
    public function updateThumbs()
    {
        $cliparts = Clipart::all();
        foreach ($cliparts as $clipart) {
            $clipart->thumb = SVG::fromString($clipart->colourways->where('colour_name', '=', 'baseline')->first()->data)->toRasterImage(75, 75);
            $clipart->save();
        }
    }

    /**
     * Import a zip file containing properly structured and named files for import.
     * Each clipart is described by a csv or xlsx file containing metadata
     * and SVG files named with the base filename contained in the metadata file plus '_<colour>.svg' where <colour> is one of '0', 'Grey', 'Blue', 'Red', 'Green', 'Purple', 'Yellow', 'Outline'
     * @param Request $request
     * @return string
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     */
    public function bulkImport(Request $request)
    {
        // clean up any previous folders

        foreach (Storage::disk('local')->directories('import') as $old_dir) {
            Storage::deleteDirectory($old_dir);
        }

        $file = $request->file('zipfile');
        if (!(Storage::disk('local')->put('upload' . DIRECTORY_SEPARATOR . $file->getFilename(), \File::get($file)))) {
            return '-1';
        }

        // make a temp folder name
        $foldername = 'import/' . uniqid();
        $zip = Madzipper::make($file->getPathname());
        $zip->extractTo(Storage::disk('local')->path($foldername));

        // go through the metadata files
        // list all files
        $files = Storage::files($foldername);
        //find metadata files- they're either CSV or .xlsx
        $metadata_files = array_filter($files, function ($k) {
            return Str::endsWith($k, ['.csv', 'xlsx']);
        });
        foreach ($metadata_files as $metadata_file) {
            // this will be a CSV
            // open the metadata file

            if (($handle = fopen(Storage::path($metadata_file), "r")) !== FALSE) {
                $clipart_data = ['owner_id' => auth()->user()->id, 'type' => 'svg'];
                $tags = [];
                $filename = '';
                //if it's an XLSX file
                if (Str::endsWith($metadata_file, ['xlsx'])) {
                    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(Storage::path($metadata_file));
                    $worksheet = $spreadsheet->getActiveSheet();
                    // Get the highest row and column numbers referenced in the worksheet
                    $highestRow = $worksheet->getHighestRow(); // e.g. 10
                    $highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
                    $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
                    for ($row = 1; $row <= $highestRow; ++$row) {
                        $value = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
                        switch ($value) {
                            case 'name':

                                $clipart_data['name'] = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
                                break;
                            case 'filename':
                                $filename = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
                                break;
                            case 'description':
                                $clipart_data['description'] = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
                                break;
                            case 'tags':
                                $tags = [];
                                for ($col = 2; $col <= $highestColumnIndex; ++$col) {
                                    if (strlen($worksheet->getCellByColumnAndRow($col, $row)->getValue()) > 0) {
                                        $tags[] = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                                    }
                                }
                                // dd($tags);
                                break;
                            case 'citations':
                                $citationsdata = [];
                                for ($col = 2; $col <= $highestColumnIndex; ++$col) {
                                    if (strlen($worksheet->getCellByColumnAndRow($col, $row)->getValue()) > 0) {
                                        $citationsdata[] = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                                    }

                                }
                                // build a nice HTML citation string to display
                                $clipart_data['citations'] = "<ul><li>";
                                $clipart_data['citations'] .= implode("</li><li>", $citationsdata);
                                $clipart_data['citations'] .= "</li></ul>";
                                $clipart_data['citations'] = utf8_encode($clipart_data['citations']);
                                break;
                            case 'paid':
                                //$clipart_data['paid'] = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
                                break;
                            default:
                                break;
                        }

                    }
                    // else it's a CSV filr
                } elseif (Str::endsWith($metadata_file, ['csv'])) {
                    while (($data = fgetcsv($handle)) !== FALSE) {
                        // the first data cell is the header
                        switch ($data[0]) {
                            case 'name':
                                if (!isset($data[1])) {
                                    Storage::delete($files);
                                    return redirect()->route('admin.clipart.index')->withFlashDanger("Metadata file {$metadata_file} has empty name field. Aborting upload");
                                }
                                $clipart_data['name'] = $data[1];
                                $clipart_data['description'] = $data[1];
                                break;
                            case 'filename':
                                // this is critical
                                if (!isset($data[1])) {
                                    Storage::delete($files);
                                    return redirect()->route('admin.clipart.index')->withFlashDanger("Metadata file {$metadata_file} has empty filename field. Aborting upload");
                                }
                                $filename = $data[1];
                                break;
                            case 'description':
                                if (isset($data[1])) {
                                    $clipart_data['description'] = $data[1];
                                }

                                break;
                            case 'tags':
                                $tags = $data;
                                //  remove the first element, it's the header
                                array_shift($tags);
                                break;
                            case 'citations':
                                //  remove the first element, it's the header
                                array_shift($data);
                                // build a nice citation string to display
                                $filtered_citations = array_filter($data, function ($k) {
                                    return strlen($k) > 0;
                                });
                                $clipart_data['citations'] = "<ul><li>";
                                $clipart_data['citations'] .= implode("</li><li>", $filtered_citations);
                                $clipart_data['citations'] .= "</li></ul>";
                                $clipart_data['citations'] = utf8_encode($clipart_data['citations']);
                                break;
                            case 'paid':
                                if (isset($data[1])) {
                                    $clipart_data['paid'] = $data[1];
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }

                // dd($tags);
                // make the clipart entry (or update if there's something with this name already)
                try {
                    $clipart = Clipart::updateOrCreate(['name' => $clipart_data['name']], $clipart_data);
                    //sync tags

                    $tagsSyncArr = [];
                    foreach ($tags as $tag) {
                        $tagsSyncArr[] = Tag::firstOrCreate(['text' => $tag])->id;
                    }
                    $clipart->tags()->sync($tagsSyncArr);

                    // make the colourways
                    // find the baseline file
                    if (Storage::disk('local')->exists($foldername . DIRECTORY_SEPARATOR . $filename . '_0.svg')) {
                        Clipart_colourway::updateOrCreate(['clipart_id' => $clipart->id, 'colour_name' => 'baseline', 'colour' => '#000000'], ['data' => Storage::disk('local')->get($foldername . DIRECTORY_SEPARATOR . $filename . '_0.svg'),]);
                    }

                    // blue
                    if (Storage::disk('local')->exists($foldername . DIRECTORY_SEPARATOR . $filename . '_Blue.svg')) {
                        Clipart_colourway::updateOrCreate(['clipart_id' => $clipart->id, 'colour_name' => 'blue', 'colour' => '#0000FF'], ['data' => Storage::disk('local')->get($foldername . DIRECTORY_SEPARATOR . $filename . '_Blue.svg'),]);
                    }

                    //green
                    if (Storage::disk('local')->exists($foldername . DIRECTORY_SEPARATOR . $filename . '_Green.svg')) {
                        Clipart_colourway::updateOrCreate(['clipart_id' => $clipart->id, 'colour_name' => 'green', 'colour' => '#006400'], ['data' => Storage::disk('local')->get($foldername . DIRECTORY_SEPARATOR . $filename . '_Green.svg'),]);
                    }

                    //grey
                    if (Storage::disk('local')->exists($foldername . DIRECTORY_SEPARATOR . $filename . '_Grey.svg')) {
                        Clipart_colourway::updateOrCreate(['clipart_id' => $clipart->id, 'colour_name' => 'grey', 'colour' => '#A9A9A9'], ['data' => Storage::disk('local')->get($foldername . DIRECTORY_SEPARATOR . $filename . '_Grey.svg'),]);
                    }

                    //purple!
                    if (Storage::disk('local')->exists($foldername . DIRECTORY_SEPARATOR . $filename . '_Purple.svg')) {
                        Clipart_colourway::updateOrCreate(['clipart_id' => $clipart->id, 'colour_name' => 'purple', 'colour' => '#9400D3'], ['data' => Storage::disk('local')->get($foldername . DIRECTORY_SEPARATOR . $filename . '_Purple.svg')]);
                    }

                    //red, the blood of angry men!
                    if (Storage::disk('local')->exists($foldername . DIRECTORY_SEPARATOR . $filename . '_Red.svg')) {
                        Clipart_colourway::updateOrCreate(['clipart_id' => $clipart->id, 'colour_name' => 'red', 'colour' => '#8B0000'], ['data' => Storage::disk('local')->get($foldername . DIRECTORY_SEPARATOR . $filename . '_Red.svg')]);
                    }

                    //lellow
                    if (Storage::disk('local')->exists($foldername . DIRECTORY_SEPARATOR . $filename . '_Yellow.svg')) {
                        Clipart_colourway::updateOrCreate(['clipart_id' => $clipart->id, 'colour_name' => 'yellow', 'colour' => '#FFD700'], ['data' => Storage::disk('local')->get($foldername . DIRECTORY_SEPARATOR . $filename . '_Yellow.svg')]);
                    }

                    //outline
                    if (Storage::disk('local')->exists($foldername . DIRECTORY_SEPARATOR . $filename . '_Outlines.svg')) {
                        Clipart_colourway::updateOrCreate(['clipart_id' => $clipart->id, 'colour_name' => 'outline', 'colour' => '#000000'], ['data' => Storage::disk('local')->get($foldername . DIRECTORY_SEPARATOR . $filename . '_Outlines.svg')]);
                    }
                } catch (\Exception $e) {
                    // do nothing
                }

            }
        }

        // clean up
        Storage::delete($files);
        return redirect()->route('admin.clipart.index')->withFlashSuccess('Clipart uploaded success!');
    }

/////////////////////////////////////////////////////////////////////////////////////////
///
/// Private (internal) helper functions
///
/// //////////////////////////////////////////////////////////////////////////////////////

    /**
     * Recurse function to tag scale elements
     * @param $child
     */
    private function recurse($child)
    {
        foreach ($child->children() as $children) {
            $children['is_scale'] = 'true';
            $this->recurse($children);
        }
        return;
    }
}
