@if($edit)
    <div class="mceNonEditable component-container componentLayout" data-component-key="componentLayout">
        <a href="#" class="btn btn-danger pull-right delete-component">X</a>
        <h4>@lang('hilco::app.componentLayout')</h4>
        <div class="row component-tiles-container">
            @foreach($tiles as $tileId => $tile)
                <div data-tile-id="{{ $tileId }}"
                     @if( $tile['tileSize'] !== null) data-tile-size="{{ $tile['tileSize']}}" @else data-tile-size="12" @endif
                     class="component-tile-container col-sm-12 col-md-4">

                    <div id="component-area-{{ $tileId }}" class="component-area">
                        @if(isset($tile['component']))
                            @include($tile['component'], $tile['data'])
                        @endif
                    </div>

                    <button class="btn btn-primary select-component-button" data-linked-component="#component-area-{{ $tileId }}">Select a Component</button>
                </div>
            @endforeach
        </div>
        <h4 class="current-component-layout" @if($selectedLayout !== null) data-current-layout="{{ $selectedLayout }}" @else data-current-layout="full" @endif
        @if($displayName !== null) data-display-name="{{ $displayName }}" @else data-display-name="100%" @endif>
            @if($displayName !== null ) Current Layout: {{ $displayName }} @else Current Layout: 100% @endif</h4>
        <button id="changeLayout2" class="btn btn-info">Change Layout</button>
    </div>
@endif

@if($script)
    <script type="text/javascript">
        registerComponent('componentLayout', {
            menuText: '@lang('hilco::app.componentLayout')',
            bladeTemplate: 'hilco::components.componentLayout',
            init: function (body) {
                var layouts = {
                    full:{
                        display_name : '100%',
                        total_tiles : 1,
                        tile_size_values :[12]
                    },
                    halves:{
                        display_name : '50% | 50%',
                        total_tiles : 2,
                        tile_size_values :[6, 6]
                    },
                    thirds: {
                        display_name : '33% | 33% | 33%',
                        total_tiles : 3,
                        tile_size_values: [4, 4, 4]
                    },
                    oneAndTwo: {
                        display_name : '33% | 66%',
                        total_tiles : 2,
                        tile_size_values: [4, 8]
                    },
                    twoAndOne: {
                        display_name : '66% | 33%',
                        total_tiles : 2,
                        tile_size_values: [8, 4]
                    }
                };
                function buildMenu() {
                    var menu = {};
                    $.each(_visionwareComponents, function (key, component) {
                        if(component.bladeTemplate !== 'hilco::components.componentLayout')
                            menu[component.bladeTemplate] = component.menuText;
                    });
                    return menu;
                }

                $(body).on('click', '#changeLayout2', function () {
                    var mainComponent = $(this).closest('.component-container');

                    var message = "Choose a layout for the content.";
                    var layout = $(mainComponent).find('h4.current-component-layout').attr('data-current-layout');
                    if(layout == null) layout = "";

                    swal({
                        title: "Change Layout",
                        type: "info",
                        html: message,
                        input: 'select',
                        inputOptions: {
                            full: '100%',
                            halves: '50% | 50%',
                            thirds:'33% | 33% | 33%',
                            oneAndTwo: '33% | 66%',
                            twoAndOne:'66% | 33%'
                        },
                        inputPlaceholder: 'Select a layout',
                        inputValue: layout,
                        confirmButtonClass: "btn-primary",
                        showCancelButton: true,
                        allowOutsideClick: false,
                    }).then(
                        function(inputValue){
                            var current_layout = layouts[layout];
                            var chosen_layout = layouts[inputValue];
                            if(current_layout != chosen_layout){

                                $(mainComponent).find('h4.current-component-layout').attr('data-current-layout', inputValue);
                                $(mainComponent).find('h4.current-component-layout').attr('data-display-name', layouts[inputValue]['display_name']);
                                $(mainComponent).find('h4.current-component-layout').html('Current Layout: '+ layouts[inputValue]['display_name']);

                                //change the tiles and assign the size
                                if(current_layout['total_tiles'] > chosen_layout['total_tiles']){
                                    var tilesToRemove = current_layout['total_tiles'] - chosen_layout['total_tiles'];
                                    for (let step = 0; step < tilesToRemove; step++) {
                                        var lastTile = $(mainComponent).find('div.component-tile-container').last();
                                        $(lastTile).remove();
                                    }
                                }else if(current_layout['total_tiles'] < chosen_layout['total_tiles']){
                                    var tilesToAdd = chosen_layout['total_tiles'] - current_layout['total_tiles'];
                                    for (let step = 0; step < tilesToAdd; step++) {
                                        var lastTile = $(mainComponent).find('div.component-tile-container').last();
                                        var newTileId = lastTile.data('tile-id') + 1;
                                        var newTile = lastTile.clone().attr('data-tile-id', newTileId);
                                        newTile.find('.component-area').attr('id', 'component-area-'+newTileId);
                                        newTile.find('.component-area').html('');
                                        newTile.find('.select-component-button').attr('data-linked-component', '#component-area-'+newTileId);
                                        $(mainComponent).find('.component-tiles-container').append(newTile);
                                    }
                                }

                                var loops = 0;

                                $(mainComponent).find('.component-tile-container').each(function () {

                                    var tileSize = chosen_layout['tile_size_values'][loops];
                                    $(this).attr('data-tile-size', tileSize);
                                    loops++;
                                });
                            }
                        });
                }).on('click', '.select-component-button', function () {
                    var mainComponent = $(this).closest('.component-container');
                    var linkedComponent = $(this).data('linked-component');
                    var componentTile = $(mainComponent).find(linkedComponent);

                    var message = "Choose a component for the layout.";
                    var component = $(this).attr('data-current-component');
                    if(component == null) component = "";

                    swal({
                        title: "Select a Component",
                        type: "info",
                        html: message,
                        input: 'select',
                        inputOptions: buildMenu(),
                        inputPlaceholder: 'Select a Component',
                        inputValue: component,
                        confirmButtonClass: "btn-primary",
                        showCancelButton: true,
                        allowOutsideClick: false,
                    }).then(
                        function(inputValue){
                            $.ajax({
                                url: '{{ route('landing.component') }}',
                                type: 'GET',
                                data: {
                                    _token: _csrf_token,
                                    component: inputValue,
                                },
                                success: function (data) {
                                    $(componentTile).html(data);
                                },error: function (jqXHR, exception){

                                }
                            })
                        });
                });
            },
            serialize: function (componentNode) {

                var selectedLayout = $(componentNode).find('h4.current-component-layout').data('current-layout');
                var displayName = $(componentNode).find('h4.current-component-layout').data('display-name');

                var data = {
                    selectedLayout: selectedLayout,
                    displayName: displayName,
                    tiles: {},
                };
                $(componentNode).find('.component-tile-container').each(function () {
                    var tileId = $(this).data('tile-id');
                    var component = $(this).find('[data-component-key]');
                    var key = component.data('component-key');
                    if(key != null){
                        var componentData = _visionwareComponents[key].serialize(component);
                        var bladeTemplate = _visionwareComponents[key].bladeTemplate;
                        componentData['isInLayout'] = true;
                    }else{
                        var componentData = null;
                        var bladeTemplate = null;
                    }

                    data.tiles[tileId] = {
                        tileSize: $(this).data('tile-size'),
                        component: bladeTemplate,
                        data: componentData
                    };

                });
                return data;
            },
        });
    </script>
@endif

@if($view)
    <div class="row container center-block">
        @foreach ($tiles as $tile)
            <div class="col-tn-12 col-xs-8 col-xs-offset-2 @if(!isset($tile['tileSize'])) col-sm-4  @else col-sm-{{$tile['tileSize']}} @endif col-sm-offset-0">
                @if($tile['component'] != null)
                    @include($tile['component'], $tile['data'])
                @endif
                <div class="visible-tn visible-xs">
                    <br>
                </div>
            </div>
        @endforeach
        <div class="clearfix" style="margin-bottom: 20px"></div>
    </div>
@endif
