import { HttpClient } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatSort, MatSortModule } from '@angular/material/sort';
import { MatTableDataSource, MatTableModule } from '@angular/material/table';
import { Router, ActivatedRoute, RouterLink } from '@angular/router';
import { AuthService } from 'src/app/auth/auth.service';
import { Layer } from 'src/app/models/layer.model';
import { Record } from 'src/app/models/record.model';
import { environment } from 'src/environments/environment';
import { MatIconModule } from '@angular/material/icon';
import { MatOptionModule } from '@angular/material/core';
import { MatSelectModule } from '@angular/material/select';
import { NgIf, DecimalPipe } from '@angular/common';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatCardModule } from '@angular/material/card';

@Component({
  selector: 'diunabi-layer-edit',
  templateUrl: './layer-edit.component.html',
  styleUrls: ['./layer-edit.component.scss'],
  standalone: true,
  imports: [FormsModule, ReactiveFormsModule, MatCardModule, MatToolbarModule, MatButtonModule, RouterLink, MatGridListModule, MatFormFieldModule, MatInputModule, NgIf, MatSelectModule, MatOptionModule, MatIconModule, MatTableModule, MatSortModule, DecimalPipe]
})
export class LayerEditComponent implements OnInit {

  public form!: UntypedFormGroup;
  private document!: Layer;

  displayedColumns = environment.views.layers.recordColumns.split("|");
  dataSource!: MatTableDataSource<Record>;

  @ViewChild(MatSort) sort!: MatSort;

  constructor(
    private fb$: UntypedFormBuilder,
    private router$: Router,
    private http$: HttpClient,
    private route$: ActivatedRoute,
    private auth$: AuthService
  ) {
    this.form = Layer.getForm(this.fb$);
  }

  async ngOnInit() {
    this.document = await this.load();
  }

  private async load(): Promise<Layer> {
    return await Layer.getById(this.route$.snapshot.paramMap.get('id') || "", this.http$);
  }
  async save() {
    if (this.form.invalid) {
      return;
    }
    this.document.loadForm(this.form);
    const id = await Layer.add(this.document, this.http$);
    this.router$.navigate(['../../Detail', id], { relativeTo: this.route$ });
  }

  trackByUid(index: number, item: Record) {
    return item.id;
  }
}
