import { Location } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormsModule, NgForm, Validators } from '@angular/forms';
// import { UniqueSelectionDispatcher } from '@angular/material';
import { ActivatedRoute, Router } from '@angular/router';

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

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

import { TranslateService } from '@ngx-translate/core';
import { ILanguage, ILanguages } from '../core/shared/language/language.model';
import { LanguageService } from '../core/shared/language/language.service';

import { BaseComponent } from '../core/components/base.component';

@Component({
    // providers: [UniqueSelectionDispatcher],
    selector: 'knk-registration',
    styleUrls: ['./registration.component.scss'],
    templateUrl: './registration.component.html'
})
export class RegistrationComponent extends BaseComponent implements OnInit {
    user: IUser;
    submitAttempt: boolean = false;
    registrationError: { id: number, msg: string } = null;
    languages: ILanguage[];
    phoneFull: string;
    phoneFocused: boolean = false;

    constructor(
        protected userService: UserService,
        private translateService: TranslateService,
        private tokenService: TokenService,
        private router: Router,
        // private location: Location,
        private countryService: CountryService,
        private languageService: LanguageService,
        route: ActivatedRoute) {
            super(userService, route);
        this.user = new User();
    }
    ngOnInit(): void {
        super.ngOnInit();
        // this.location.replaceState(`/${this.lang}/registration`);
        this.countryService.Country.subscribe((country: ICountry) => {
            if (country) {
                this.user.countryId = country.countryId;
                this.user.phonePrefix = country.phonePrefix;
                this.phoneFull = country.phonePrefix;
            } else {
                console.log('Country code is not found');
            }
        });
        this.languageService.Languages.subscribe((languages: ILanguages) => {
            this.languages = languages.items;
            languages.items.forEach(function(lang: ILanguage, key: number): void {
                if (lang.languageCode === this.lang) {
                    this.user.languageId = lang.languageId;
                    return;
                }
            }, this);
        });
    }
    register(): void {
        // e.preventDefault();
        this.registrationError = null;

        this.user.isUSTaxEntity = false;
        this.user.kycApproved = false;
        this.user.phoneVerified = false;
        this.user.mailVerfied = false;
        this.user.termsOfServiceChecked = false;

        this.userService.createUser(this.user).subscribe(
            (user) => {
                console.log('registered, login and go to dashboard');
                this.tokenService.apiUserToken(user).subscribe(() => {
                    const langParamName: string = 'lang';
                    this.router.navigate([this.route.snapshot.params[langParamName], `feeds`]);
                });
            },
            (err) => {
                this.registrationError = err.error;
            });
    }
    onSubmit(f: NgForm): void {
        // console.log(f.value);  // { first: '', last: '' }
        // console.log(f.valid);  // false
        this.submitAttempt = true;
        if (f.valid) {
            this.register();
        } else {
            this.registrationError = { id: -1, msg: 'Please fill all required fields.' };
        }
    }
    getErrorMessage(p: FormControl, key: string): string {
        if (p.hasError('required')) {
            if (key) {
                return 'You must enter a value for \"' + this.translateService.instant(key) + '\"';
            } else {
                return 'You must enter a value';
            }
        }
        if (p.hasError('patternInvalid')) {
            return 'Input format is invalid';
        }
        // let val: string = 'You must enter a value for ' +  this.translateService.instant['[user name]'];
        // if (name) {
        //    this.translateService.get('[user name]').flatMap((res: string)  => {
        //        console.log('dddddddddd');
        //        return val += name + res;
        //    });
        // }
        // return p.hasError('required') ? 'You must enter a value' :
        //    p.hasError('email') ? 'Not a valid email' : '';
    }
    parsePhone(): void {
        if (this.phoneFull) {
            let p: string = this.phoneFull.replace(/\s+|-|\+/g, '');
            if (p.length >= 7) {
                this.user.phonePrefix = p.substr(0, p.length - 7);
                this.user.phone = p.substr(p.length - 7);
            }
        }
    }
}
