import { Component, OnInit,
  ChangeDetectorRef, ChangeDetectionStrategy, ViewChild } from '@angular/core'
import { UntypedFormGroup, UntypedFormControl } from '@angular/forms'
import { ActivatedRoute } from '@angular/router'

import { MatTableDataSource } from '@angular/material/table'
import { MatSnackBar } from '@angular/material/snack-bar'
import { MatSort } from '@angular/material/sort'
import { MatPaginator } from '@angular/material/paginator'
import { MatDialog } from '@angular/material/dialog'

import { AdminDataService } from '../../admin-data.service'
import { AdminManageDataService } from '../data.service'
import { GisafAdminProjectDialogComponent } from './dialog.component'
import { AuthenticationService } from '../../../_services/authentication.service'
import { ProjectField, projectFields } from './fields'
import { Project } from '../../../openapi'


@Component({
    selector: 'gisaf-admin-project',
    templateUrl: './project.component.html',
    styleUrls: ['./project.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProjectComponent implements OnInit {
    edit_roles = ['project manager']
    projects: Project[] = []
    fields: string[] = projectFields.map(f=>f.name)
    actions: string[] = [
        'edit',
        'delete'
    ]
    columns: string[]
    dataSource: MatTableDataSource<object>
    @ViewChild(MatSort, {static: true}) sort: MatSort
    @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator
    unlockDeleteFormGroup: UntypedFormGroup = new UntypedFormGroup({})
    filterText: string

    constructor(
        private cdr: ChangeDetectorRef,
        private route: ActivatedRoute,
        public authenticationService: AuthenticationService,
        private snackBar: MatSnackBar,
        private dataService: AdminDataService,
        private adminManageDataService: AdminManageDataService,
        public dialog: MatDialog,
    ) {}

    ngOnInit(): void {
        this.route.data.subscribe(
            data => {
                this.projects = data['projects']
                this.dataSource = new MatTableDataSource(this.projects)
                this.dataSource.sort = this.sort
                this.dataSource.paginator = this.paginator
                this.cdr.markForCheck()
            }
        )
        this.unlockDeleteFormGroup = new UntypedFormGroup({
            'canDelete': new UntypedFormControl(),
        })
        this.columns = projectFields.filter(f=>f.inTable).map(f=>f.name)
        this.authenticationService.isAuthorized(this.edit_roles).subscribe(
            isAuthorized => {
                if (isAuthorized) {
                    this.columns = this.columns.concat(this.actions)
                }
            }
        )
    }

    applyFilter() {
        this.dataSource.filter = this.filterText.trim().toLowerCase();
    }

    editItem(data?: Project) {
        const dialogRef = this.dialog.open(GisafAdminProjectDialogComponent, {
            width: '75%',
            data: {
                'project': data || {},
            }
        })
        dialogRef.afterClosed().subscribe(
            (project: Project) => project &&
                this.adminManageDataService.saveProject(
                    project
                ).subscribe(
                    (id: number) => {
                        if (data) {
                            // Update
                            let row = this.dataSource.data.findIndex(c=>c['id'] == id)
                            this.dataSource.data[row] = project
                        }
                        else {
                            // New
                            project['id'] = id
                            this.dataSource.data.push(project as Project)
                        }
                        this.dataSource.data = this.dataSource.data
                        this.dataService.getSurveyMeta().subscribe()
                        this.cdr.markForCheck()
                    },
                    err => {
                        // Popup the dialog again, the error is catched by Apollo
                        this.editItem(project)
                    }
                )
        )
    }

    deleteItem(project: Project) {
        this.adminManageDataService.deleteProject(project).subscribe(
            _ => {
                this.snackBar.open(
                    'Project ' + project.name + ' deleted',
                    'Close',
                    {duration: 3000}
                )
                // Remove from table
                let dsi = this.dataSource.data.findIndex(row => row['id'] == project.id)
                this.dataSource.data.splice(dsi, 1)
                // Force Angular change detection (??)
                this.dataSource.data = this.dataSource.data
                this.dataService.getSurveyMeta().subscribe()
                this.cdr.markForCheck()
            }
        )
    }
}
