import { Component, OnInit } from '@angular/core';

import { Location } from '@angular/common';

import { UniqueSelectionDispatcher } from '@angular/material';

import { ActivatedRoute, Router } from '@angular/router';

import { TokenService } from '../../shared';
import { ICountry } from '../../shared/country/country.model';
import { CountryService } from '../../shared/country/country.service';

import { IUser, User } from '../../shared/user/user.model';
import { UserService } from '../../shared/user/user.service';

@Component({
    providers: [UniqueSelectionDispatcher],
    selector: 'knk-registration',
    styleUrls: ['./registration.component.scss'],
    templateUrl: './registration.component.html'
})
export class RegistrationComponent implements OnInit {
    user: IUser;
    registrationError: { id: number, msg: string } = null;
    languages: { id: string, value: string }[] = [
        { value: 'English', id: 'en' },
        { value: 'Español', id: 'es' },
        { value: '中文', id: 'zh' },
        { value: 'Português', id: 'pt' },
        { value: '日本語', id: 'ja' },
        { value: 'Русский', id: 'ru' }
    ];

    constructor(
        private userService: UserService,
        private tokenService: TokenService,
        private router: Router,
        private location: Location,
        private countryService: CountryService,
        private route: ActivatedRoute) {
        this.user = new User();
    }
    ngOnInit(): void {
        let langParamName: string = 'lang';
        this.location.replaceState(`/${this.route.snapshot.params[langParamName]}/registration`); // clear query string parameters
        this.countryService.Country.subscribe((country: ICountry) => {
            if (country) {
                this.user.countryCode2 = country.countryCode2;
                this.user.languageCode = this.route.snapshot.params[langParamName];
                // console.log('Country code is ' + country.countryCode2);
            } else {
                console.log('Country code is not found');
            }
        });
        let isTestPropertyName: string = 'test';
        this.userService.testParam = this.route.snapshot.data[isTestPropertyName];
    }

    register(e: Event): void {
        e.preventDefault();
        this.registrationError = null;
        this.userService.createUser(this.user).subscribe(
            (u) => {
                console.log('registerd, login and go to dashboard');
                this.tokenService.apiUserToken(u).subscribe(() => {
                    let langParamName: string = 'lang';
                    this.router.navigate([this.route.snapshot.params[langParamName], `dashboard`]);
                });
            },
            (error) => {
                console.log(error);
                this.registrationError = error;
            });
    }
}
