import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Inject, Input, OnDestroy } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { AppService } from '@core/app.service';
import extend from 'extend';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Subscription } from 'rxjs';
import { filter } from 'rxjs/operators';
import { BIXI_I18N_TOKEN } from '../../../core/i18n/service.type';
import { I18NService } from './../../../core/i18n/service';

@Component({
  selector: 'code-box',
  templateUrl: './code-box.component.html',
  host: {
    '[class.code-box]': 'true',
    '[class.pure-code-box]': 'pure',
    '[class.expand]': 'expand'
  },
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CodeBoxComponent implements OnDestroy {
  private i18n$: Subscription;
  private _item: any;
  private _orgItem: any;
  copied = false;
  theme = 'default';

  @Input() expand: boolean = false;
  @Input() pure: boolean = false;
  constructor(
    private appService: AppService,
    @Inject(BIXI_I18N_TOKEN) private i18n: I18NService,
    private msg: NzMessageService,
    private cdr: ChangeDetectorRef,
    private sanitizer: DomSanitizer) {

    this.appService.theme$.subscribe(data => {
      this.theme = data;
      this.cdr.markForCheck();
    });
    this.i18n$ = this.i18n.change.pipe(filter(() => !!this._orgItem)).subscribe(() => {
      this.item.title = this.i18n.get(this._orgItem.meta.title);
      this.item.summary = this.i18n.get(this._orgItem.summary);
    });
  }
  @Input()
  set item(value: any) {
    if (!this._orgItem) {
      this._orgItem = extend(true, {}, value);
    }
    const ret: any = {
      meta: value.meta,
      code: value.code.trim(),
      title: this.i18n.get(value.meta.title),
      summary: this.sanitizer.bypassSecurityTrustHtml(this.i18n.get(value.summary)),
      browser: +value.meta.browser > 0 ? +value.meta.browser : null,
      bg: value.meta.bg,
      urls: value.urls
    };
    this._item = ret;
  }
  get item() {
    return this._item;
  }

  handle() {
    this.expand = !this.expand;
  }

  onCopy(value: string) {
    this.copy(value).then(() => {
      this.msg.success(this.i18n.fanyi('app.demo.copied'));
      this.copied = true;
      setTimeout(() => (this.copied = false), 1000);
    });
  }

  /**
   * 复制字符串文档至剪贴板
   */
  copy(value: string): Promise<string> {
    return new Promise<string>((resolve): void => {
      let copyTextArea: HTMLTextAreaElement | null = null;
      try {
        copyTextArea = document.createElement('textarea');
        copyTextArea.style.height = '0px';
        copyTextArea.style.opacity = '0';
        copyTextArea.style.width = '0px';
        document.body.appendChild(copyTextArea);
        copyTextArea.value = value;
        copyTextArea.select();
        document.execCommand('copy');
        resolve(value);
      } finally {
        if (copyTextArea && copyTextArea.parentNode) {
          copyTextArea.parentNode.removeChild(copyTextArea);
        }
      }
    });
  }

  ngOnDestroy() {
    this.i18n$.unsubscribe();
  }
}
