import { Location } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import {FormArray, FormBuilder, Validators} from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { BaseForm } from 'src/app/core/base/base-form';
import { BaseFormUid } from 'src/app/core/base/base-form-uid';
import { InsturctorPaymentAccoutService } from 'src/app/core/service/settingPayment/insturctor-payment-accout.service';
import { FacultysService } from 'src/app/core/service/settings/facultys.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';

@Component({
    selector: 'app-teacher-finance-form',
    templateUrl: './teacher-finance-form.component.html',
    styleUrls: ['./teacher-finance-form.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TeacherFinanceFormComponent extends BaseFormUid implements OnInit {
    public getArray(){
     let x = this.form.get('array') as FormArray
     return x.at(0)
    }
    facultyList: any = [];
    constructor(
        public fb: FormBuilder,
        public router: Router,
        public activeRoute: ActivatedRoute,
        public location: Location,
        private insturctorPaymentSV: InsturctorPaymentAccoutService,
        private swSV: SweetalertService,
        private cdr: ChangeDetectorRef,
        private facultySV: FacultysService
    ) {
        super(
            router,
            activeRoute,
            fb,
            location
            )
    }

    ngOnInit(): void {
        this.facultySV.getAll().pipe(
            tap(x => this.facultyList = x),
            tap(x => this.cdr.detectChanges())
        ).subscribe()
        const data = this.form.get('array') as FormArray
        switch (this.state) {
            case 'add':
                data.push(this.createArray())
                break;

            case 'edit':
                this.insturctorPaymentSV.get(this.id).pipe(
                    tap(x => data.push(this.createArray(x))),
                    tap(x => this.cdr.detectChanges())
                    ).subscribe()
                break;
        }
    }

    createForm(){
        return this.fb.group({
            array: this.fb.array([
                // this.createArray()
            ])
        })
    }

    createArray(x?){
        return this.fb.group({
            status_id: x?.status_id,
            create_by: x?.create_by,
            create_datetime: x?.create_datetime,
            updated_by: x?.updated_by,
            updated_datetime: x?.updated_datetime,
            deleted_by: x?.deleted_by,
            deleted_datetime: x?.deleted_datetime,
            instructor_payment_account_uid: x?.instructor_payment_account_uid,
            instructor_code: x?.instructor_code,
            instructor_name: x?.instructor_name,
            faculty_code: x?.faculty_code,
            faculty_name: x?.faculty_name,
            account_no: x?.account_no,
            email: [x?.email , Validators.pattern('^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$')],
            phone_no: x?.phone_no,
            remark: x?.remark
        })
    }

    save(){
        const data = this.form.get('array') as FormArray
        const form = data.getRawValue()
        switch (this.state) {
            case 'edit':
                let form2 = this.getArray()
                let data = form2.value
                this.insturctorPaymentSV.update2(data).pipe(
                    tap(x => this.swSV.updateSuccess()),
                    tap(x => window.history.back()),
                    catchError(err => {
                        this.swSV.err()
                        return throwError(err)
                    })
                ).subscribe()
                break;

            case 'add':
                this.insturctorPaymentSV.add(form).pipe(
                    tap(x => this.swSV.saveSuccess()),
                    tap(x => window.history.back()),
                    catchError(err => {
                        this.swSV.err()
                        return throwError(err)
                    })
                ).subscribe()
                break;
        }
    }

    cancel(){
        this.back()
    }

    add(){
        const form = this.form.get('array') as FormArray
        form.push(this.createArray())
    }
}
