import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {AuthService} from '../../../classes/auth.service';
import {TypesService} from '../../basic/types/types.service';
import {Dialog} from '../../../classes/dialog';
import {repairErrors, setErrors} from '../../../classes/utils';

@Component({
    selector: 'app-signin',
    templateUrl: './signin.component.html',
    styleUrls: ['./signin.component.scss']
})
export class SigninComponent implements OnInit {
    public loading = false;
    usernameCtrl = new FormControl('', [Validators.required]);
    type;
    passwordCtrl = new FormControl('', [Validators.required, Validators.minLength(5)]);
    public form: FormGroup;
    remember: boolean = false;

    /**
     * @param {FormBuilder} fb marbot be form
     * @param {Router} router baray navigate kardan hast
     * @param {HttpClient} http baray darkhast hay http estefade mishe
     * @param {AuthService} auth baray moshakhas kardan inke login hast ya na
     * @param {TypesService} typeservice baray ferestadan type be server baray login
     * @param {AppsService} appservice  baray  ferestadan version va ... baray login
     */
    constructor(
        private fb: FormBuilder,
        private router: Router,
        private http: HttpClient,
        private auth: AuthService,
        private typeservice: TypesService,
        private dialog: Dialog,
        private authService: AuthService,
    ) {
        this.type = this.typeservice.new();
        this.type.id = '3';
    }

    ngOnInit() {
        this.form = this.fb.group({
            usernameCtrl: this.usernameCtrl,
            passwordCtrl: this.passwordCtrl,
        });

    }

    onSubmit() {
        this.loading = true;
        this.auth.login(this.form.controls['usernameCtrl'].value,
            this.form.controls['passwordCtrl'].value
            , '3', this.auth.firebase, this.remember)
            .subscribe(
                loggedIn => {
                    if (loggedIn) {
                        console.log('salam');
                        this.loading = false;
                        this.router.navigateByUrl('');
                    }
                },
                error => {
                    console.log('errors', error);
                    this.loading = false;
                    let errors = error.json().errors;
                    setErrors(repairErrors(errors), this.form.controls, this.dialog);
                });
    }
}


