import { Component, ElementRef, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { IAccount, IUser, LoaderService, RouterExtService, TokenService, UserService } from '../core/shared';
import { ILanguage, ILanguages } from '../core/shared/language/language.model';
import { LanguageService } from '../core/shared/language/language.service';
import { AbstractControl, FormBuilder, FormGroup, NgModel } from '@angular/forms';
import { TranslateService } from '@ngx-translate/core';
import { IUserAccounts } from '../core/shared/user/user.model';
import { has as _has, forIn as _forIn } from 'lodash/object';
import { Subject } from 'rxjs/Subject';

interface IUploadFile extends EventTarget {
  files: Blob[];
  result: string;
}

@Component({
  selector: 'knk-my-account',
  templateUrl: './myaccount.component.pug',
  styleUrls: ['./myaccount.component.scss']
})
export class MyAccountComponent implements OnInit {
  lang: string;
  user: IUser;
  userForm: FormGroup;
  uploadedImage: string;
  registrationError: { id: number, msg: string } = null;
  uniqueId: number;

  get userHasAvatar(): boolean {
    if (_has(this.user, ['hasAvatar']) && _has(this.user, ['avatarUrl'])) {
      return Boolean(this.user.hasAvatar) && (typeof this.user.avatarUrl === 'string' && this.user.avatarUrl.length > 0);
    }
    return false;
  }

  get userHasUploadImage(): boolean {
    if (typeof this.uploadedImage === 'string' && this.uploadedImage.length > 0) {
      return true;
    }
    return false;
  }

  get userAvatarUrl(): string | null {
    if (this.userHasUploadImage) {
      return this.uploadedImage;
    } else if (this.userHasAvatar) {
      return `${SETTINGS.API_URL}${this.user.avatarUrl}?${this.uniqueId}`;
    }
    return null;
  }

  private ngUnsubscribe: Subject<void> = new Subject<void>();

  constructor(private route: ActivatedRoute,
              private userService: UserService,
              private tokenService: TokenService,
              private routerExt: RouterExtService,
              private languageService: LanguageService,
              private translateService: TranslateService,
              private fb: FormBuilder) {
  }

  ngOnInit(): void {
    this.uniqueId = Date.now();
    this.lang = this.translateService.currentLang || this.translateService.defaultLang;

    if (!this.tokenService.isLogin) {
      this.routerExt.goToPage(['login']);
    }

    this.userForm = this.fb.group({
      email: this.fb.control({value: '', disabled: true}),
      userName: this.fb.control(''),
      content: this.fb.control(''),
      contentBase64: this.fb.control('')
    });
    this.userForm.updateValueAndValidity({emitEvent: false});

    this.userService.userChanged
      .takeUntil(this.ngUnsubscribe)
      .subscribe((user: IUser): void => {
        this.uniqueId = Date.now();
        // console.warn(user);
      });

    if (this.tokenService.isLogin) {
      this.userService.loadUser()
        .take(1)
        .subscribe(accounts => {
          if (_has(accounts, ['user'])) {
            let user: IUser = accounts.user;
            this.user = user;
            this.userForm.controls.email.patchValue(this.user.email, {emitEvent: false});
            this.userForm.controls.userName.patchValue(this.user.userName, {emitEvent: false});
            // console.warn(user);
          }
        });
    }
  }

  onSubmit(form: FormGroup): void {
    if (this.userForm.valid) {
      // console.warn(this.userForm.value);
      let updatedUser: IUser = Object.assign({}, this.user, this.userForm.value);
      /*_forIn(this.userForm.controls, (value: string, key: string): void => {
        if (!this.userForm.controls[key].disabled && this.userForm.controls[key].dirty) {
          updatedUser[key] = value;
        }
      });*/
      // console.warn(updatedUser);

      this.userService.updateUser(updatedUser)
        .take(1)
        .subscribe((user: IUser): void => {
          this.user = user;
          this.userForm.controls.email.patchValue(this.user.email, {emitEvent: false});
          this.userForm.controls.userName.patchValue(this.user.userName, {emitEvent: false});

          this.uploadedImage = undefined;
          this.userForm.controls.content.patchValue('', {emitEvent: false});
          this.userForm.controls.contentBase64.patchValue('', {emitEvent: false});
          // console.warn(user);
        }, (response: any): void => {
          this.registrationError = response.error;
        });
    }
  }

  readUrl(event: Event): void {
    let target: HTMLInputElement = event.target as HTMLInputElement;
    let reader: FileReader = new FileReader();

    if (target.files && target.files[0]) {
      reader.onload = (event: ProgressEvent): void => {
        let target: FileReader = event.target as FileReader;
        if (target.result && (target.result.substr(0, 11) === 'data:image/')) {
          this.uploadedImage = target.result;

          let content: string = this.uploadedImage.substr(this.uploadedImage.indexOf('base64,') + 7);
          this.userForm.controls.content.patchValue(content, {emitEvent: true});
          this.userForm.controls.contentBase64.patchValue(content, {emitEvent: true});
        }
      };

      reader.readAsDataURL(target.files[0]);
    }
  }
}
