import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';

import {Store} from '@ngrx/store';

import {AuthService} from '../auth.service';
import {takeUntil, tap} from 'rxjs/operators';
import {noop, Subject} from 'rxjs';
import {ActivatedRoute, Router} from '@angular/router';
import {AppState} from '../../reducers';
import {login} from '../auth.actions';
import {AuthActions} from '../action-types';
import { matxAnimations } from 'app/shared/animations/matx-animations';
import { AppLoaderService } from 'app/shared/services/app-loader/app-loader.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  animations: matxAnimations

})
export class LoginComponent implements OnInit {
    signinForm: FormGroup;
    errorMsg = '';
    return: string;
    loading: Boolean;

    private _unsubscribeAll: Subject<any>;
    constructor(
        private auth: AuthService,
        private matxLoader: AppLoaderService,
      private router: Router,
      private route: ActivatedRoute,
      private store: Store<AppState>
    ) {
      this._unsubscribeAll = new Subject();
    }

    ngOnInit() {
      this.signinForm = new FormGroup({
        username: new FormControl('Watson', Validators.required),
        password: new FormControl('12345678', Validators.required),
        //rememberMe: new FormControl(true)
      });

      this.route.queryParams
        .pipe(takeUntil(this._unsubscribeAll))
        .subscribe(params => this.return = params['return'] || '/');
    }

    ngAfterViewInit() {
      // setTimeout(() => {
        //this.autoSignIn();
      // })
    }

    // tslint:disable-next-line: use-lifecycle-interface
    ngOnDestroy() {
      this._unsubscribeAll.next();
      this._unsubscribeAll.complete();
    }

    signin() {
    //   const signinData = this.signinForm.value;
    //   this.loading = true;
    //   this.jwtAuth.signin(signinData.username, signinData.password)
    //   .subscribe(response => {
    //     this.loading = false;
    //     this.router.navigateByUrl(this.return);
    //   }, err => {
    //     this.loading = false;
    //     this.errorMsg = err.message;
    //   })
    const val = this.signinForm.value;

      this.auth.login(val.email, val.password)
          .pipe(
              tap(user => {

                  console.log(user);

                  this.store.dispatch(login({user}));

                  this.router.navigateByUrl('/dashboard/analytics');

              })
          )
          .subscribe(
              noop,
              () => alert('Login Failed')
          );

    }

    autoSignIn() {
      if (this.return === '/') {
        return;
      }
      this.matxLoader.open(`Automatically Signing you in! \n Return url: ${this.return.substring(0, 20)}...`, {width: '320px'});
      setTimeout(() => {
        this.signin();
        console.log('autoSignIn');
        this.matxLoader.close();
      }, 2000);
    }
//   form: FormGroup;

//   constructor(
//       private fb: FormBuilder,
//       private auth: AuthService,
//       private router: Router,
//       private store: Store<AppState>) {

//       this.form = fb.group({
//           email: ['test@angular-university.io', [Validators.required]],
//           password: ['test', [Validators.required]]
//       });

//   }

//   ngOnInit() {

//   }

//   login() {

//       const val = this.form.value;

//       this.auth.login(val.email, val.password)
//           .pipe(
//               tap(user => {

//                   console.log(user);

//                   this.store.dispatch(login({user}));

//                   this.router.navigateByUrl('/dashboard/analytics');

//               })
//           )
//           .subscribe(
//               noop,
//               () => alert('Login Failed')
//           );



//   }

}

