import {Component, OnInit, ViewContainerRef} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import {AuthService} from './classes/auth.service';
import {Router} from '@angular/router';
import {Dialog} from './classes/dialog';
import {ToasterConfig} from 'angular5-toaster/dist';
import {JsonapiCore} from 'ngx-jsonapi';
import {Http} from '@angular/http';
import {MessagingService} from './classes/messaging.service';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
  message;
  toasterconfig: ToasterConfig;
  test;

  constructor(translate: TranslateService,
              private authService: AuthService,
              private router: Router,
              private dialog: Dialog,
              private jsonapiCore: JsonapiCore,
              private http: Http,
              private msg: MessagingService,
  ) {
    /***
     * in vase gereftan data az background notification firebase hast
     */
    navigator.serviceWorker.addEventListener('message', function (event) {
      if (event.data.from) {
// todo type of messages
        // if (event.data.data.request)
        //     listRequest.updateRequests();
      }
    });
    this.toasterconfig = new ToasterConfig({
      limit: 5,
      showCloseButton: false,
      timeout: 5000
    });
    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 = (errors): void => {
      // this.loading = 'No connection 2!!!';
      if (errors['errors'][0]['status'] === '401') {

        this.router.navigateByUrl('/auth/signin');
        this.authService.logout();
      } else if (errors['errors'][0]['status'] === '403') {

        dialog.openForAlert('شما دسترسی ندارید.');
      } else {
        dialog.openForAlert('دسترسی به سرور را کنترل نمایید');
      }
    };
    this.msg.getPermission();
    this.msg.receiveMessage();
    this.message = this.msg.currentMessage;
  }

  ngOnInit() {
    this.authService.cloud_token.subscribe(x => {
      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();
            });
      }
    });
  }
}

