import {Component, OnInit} from '@angular/core';
import { FieldArrayType } from '@ngx-formly/core';

@Component({
  selector: 'formly-array-type',
  template: `
    <div>
      <label *ngIf="props.label" class="form-label">{{ props.label }}</label>
      <p *ngIf="props.description">{{ props.description }}</p>
      <div class="alert alert-danger" role="alert" *ngIf="showError && formControl.errors">
        <formly-validation-message [field]="field"></formly-validation-message>
      </div>
      <div class="row row-cols-1 row-cols-md-{{this.itemsPerRow}} g-1">
          <div *ngFor="let entry of field.fieldGroup; let i = index" class="col">
                <div class="card">
                    <div class="card-header">
                        <div *ngIf="props['numbered']" class="float-start">
                            <strong>{{ i + 1 }}</strong>
                        </div>
                        <div *ngIf="! this.field.props.readonly" class="btn-group float-end">
                            <button class="btn btn-primary btn-sm" [attr.disabled]="i == 0 ? 'disabled' : null" type="button" (click)="move(i, i-1)"><i-bs name="caret-up-fill"></i-bs></button>
                            <button class="btn btn-primary btn-sm" [attr.disabled]="i == this.field.fieldGroup!.length-1 ? 'disabled' : null" type="button" (click)="move(i, i+1)"><i-bs name="caret-down-fill"></i-bs></button>
                            <button class="btn btn-danger btn-sm" [attr.disabled]="field.props!['removable'] === false ? 'disabled' : null" type="button" (click)="remove(i)"><i-bs name="x-octagon-fill"></i-bs></button>
                        </div>
                    </div>
                    <div class="card-body">
                        <formly-field class="col" [field]="entry"></formly-field>
                    </div>
                </div>
            </div>
        </div>
        <button *ngIf="! this.field.props.readonly" class="btn btn-success col-sm-12" type="button" (click)="add()"><i-bs name="plus-square-fill"></i-bs></button>
    </div>
  `,
})
export class ArrayTypeComponent extends FieldArrayType implements OnInit {
    colSm: string = "col-sm-6"
    itemsPerRow = 2;
    ngOnInit() {
        if (this.field.props.hasOwnProperty('items-per-row')) {
            this.itemsPerRow = this.field.props['items-per-row']
        }
    }

    move(from: number, to: number) {
        let value_list = this.formControl.value;
        if (to >= value_list.length) {
            throw new Error("to value must be comprised between 0 and n - 1");
        }
        value_list.splice(to, 0, value_list.splice(from, 1)[0]);
        this.formControl.patchValue(value_list);
    }
}


/**  Copyright 2021 Formly. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at https://github.com/ngx-formly/ngx-formly/blob/main/LICENSE */