import { Component, ElementRef, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';

import { IAccount, IUser, LoaderService, UserService } from '../core/shared';

import { ILanguage, ILanguages } from '../core/shared/language/language.model';
import { LanguageService } from '../core/shared/language/language.service';

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

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

@Component({
  selector: 'knk-my-account',
  templateUrl: './myaccount.component.html',
  styleUrls: ['./myaccount.component.scss']
})
export class MyAccountComponent extends BaseComponent implements OnInit {
  user: IUser;
  accounts: IAccount[];
  editUser: IUser;
  edit = false;
  languages: ILanguage[];
  phoneFull: string;
  registrationError: { id: number, msg: string } = null;
  imageSrc: string;

  constructor(protected userService: UserService,
              route: ActivatedRoute,
              private languageService: LanguageService) {
    super(userService, route);
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.userService.loadUser().subscribe(userAccounts => {
      this.user = userAccounts.user;
      this.accounts = userAccounts.accounts;
      this.editUser = Object.assign({content: ''}, this.user);
      this.phoneFull = this.editUser.phonePrefix + this.editUser.phone;
      if (this.user.avatarUrl && this.user.avatarUrl !== '') {
        this.imageSrc = `${SETTINGS.API_URL}` + this.user.avatarUrl;
      }
      // this.userService.getUserAvatar(this.user.userId).subscribe(
      //     (img) => {
      //         this.imageSrc = img;
      //     }
      // );
      // this.loaderSubscription.unsubscribe();
    });

    this.languageService.Languages.subscribe((languages: ILanguages) => {
      this.languages = languages.items;
      languages.items.forEach(function (lang: ILanguage, key: number): void {
        if (this.user && lang.languageCode === this.lang) {
          this.user.languageId = lang.languageId;
          return;
        }
      }, this);
    });
  }

  toggleEditMode(isEditMode: boolean = false): void {
    if (this.edit === isEditMode) {
      return;
    }
    this.edit = isEditMode;
    if (this.edit) {
      this.editUser = Object.assign({content: ''}, this.user);
    }
  }

  save(): void {
    this.userService.updateUser(this.editUser).subscribe(() => {
        Object.assign(this.user, this.editUser);
        this.toggleEditMode(false);
      },
      (err) => {
        this.registrationError = err.error;
      }
    );
  }

  parsePhone(): void {
    if (this.phoneFull) {
      let p: string = this.phoneFull.replace(/\s+|-|\+/g, '');
      if (p.length >= 7) {
        this.editUser.phonePrefix = p.substr(0, p.length - 7);
        this.editUser.phone = p.substr(p.length - 7);
      }
    }
  }

  readUrl(event: Event): void {
    let target: IUploadFile = event.target as IUploadFile;
    let self: MyAccountComponent = this;
    if (target.files && target.files[0]) {
      let reader: FileReader = new FileReader();

      reader.onload = (evt: Event) => {
        let target2: IUploadFile = evt.target as IUploadFile;
        if (target2.result && (target2.result.substr(0, 11) === 'data:image/')) {
          self.imageSrc = target2.result;
          // const contentType: string = imageSrc.substr(imageSrc.indexOf('data:') + 5, imageSrc.indexOf(';') - 5);
          // this.knok.technical.image.contentType = contentType;
          self.editUser.content = self.imageSrc.substr(this.imageSrc.indexOf('base64,') + 7);
          self.editUser.contentBase64 = self.editUser.content;
        }
      };

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