import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, Router, UrlSegment } from '@angular/router';

import { Observable } from 'rxjs/Observable';

// import 'rxjs/add/observable/throw';
// import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { TranslateService } from '@ngx-translate/core';

@Injectable()
export class LanguageResolve implements Resolve<Observable<string>> {

    constructor(private translateService: TranslateService, private router: Router = null) { }

    resolve(route: ActivatedRouteSnapshot): Observable<string> {
        let languageParamName: string = 'lang';
        let currentLang: string = route.params[languageParamName];
        const browserLang: string = this.translateService.getBrowserLang();

        if (!currentLang || this.translateService.getLangs().indexOf(currentLang) === -1) {
            if (this.translateService.getLangs().indexOf(browserLang) === -1) {
                currentLang = this.translateService.getLangs()[0];
            } else {
                currentLang = browserLang;
            }
            // When language is not resolved add current language to the start of the current URL and redirect
            if (this.router) {
                this.router.navigateByUrl(currentLang + '/' + route.url);
            }
        } else {
            console.warn('translateService.use: ' + currentLang);
            return this.translateService.use(currentLang).map(r  => currentLang);
        }
    }
}
