import {Component, OnInit} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import {AuthService} from './public/services/auth.service';
import {Router} from '@angular/router';
import {Dialog} from './public/dialog';
import {JsonapiCore} from 'ngx-jsonapi';
import {MessagingService} from './public/services/messaging.service';

@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent implements OnInit {
  constructor(translate: TranslateService,
              private authService: AuthService,
              private router: Router,
              private jsonapiCore: JsonapiCore,
              private dialog: Dialog,
              private msg: MessagingService,
  ) {
    this.msg.getPermission();
    this.msg.receiveMessage();
    translate.addLangs(['en', 'fr']);
    translate.setDefaultLang('en');
    const browserLang: string = translate.getBrowserLang();
    translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');


    jsonapiCore.loadingsStart = (): void => {
      // this.loading = 'LOADING...';
    };
    jsonapiCore.loadingsDone = (): void => {
      // this.loading = '';
      jsonapiCore.loadingsOffline = (error): void => {
        dialog.openForAlert('دسترسی به سرور را کنترل نمایید');
      };
      // this.loading = 'No connection!!!';
    };
    jsonapiCore.loadingsError = (error): void => {
      // this.loading = 'No connection 2!!!';
      dialog.openForAlert('دسترسی به سرور را کنترل نمایید');
    };
  }


  ngOnInit() {
    this.authService.cloud_token.subscribe(
      (x: string ) => {
        if (this.authService.getNoAuthUrls().indexOf(this.router.url) === -1) {
          this.authService.init(x)
            .subscribe(
              res => {
                if (!res) {
                  // this.loading = false;
                  // this.router.navigateByUrl('/auth/signin');

                  this.authService.logout();

                }
              },
              error => {
                this.authService.logout();
              });
        }
      }
    );

  }
}
