import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NbToastrService } from '@nebular/theme';
import { first } from 'rxjs/operators';
import { HappinessBEST, HappinessWeek } from '../entity/HappinessGroup';
import { HappinessGroupService } from '../services/crudServices/happiness-group.service';
import { DateUtils } from '../utilities/date-utils';
import { StringUtils } from '../utilities/string-utils';
declare let TypeIt: any;
@Component({
  selector: 'ngx-invitation',
  templateUrl: './invitation.component.html',
  styleUrls: ['./invitation.component.scss']
})
export class InvitationComponent implements OnInit {

  constructor(
    private happinessGroupService: HappinessGroupService,
    private toastrService: NbToastrService,
    private cdr: ChangeDetectorRef,
    private route: ActivatedRoute,) { }

  // typeWriter = new TypeIt("#typingContent", {
  //   strings: ["This is my string!"],
  //   speed: 75,
  //   loop: true,
  // }).go();
  weekNo: number = -1;
  weekPadNo: string = "01";
  showCopyBtn: boolean = false;
  weekTitle: string = '真幸福';
  name: string = 'Chris';
  best: HappinessBEST;
  weeks: HappinessWeek[];
  week: HappinessWeek;
  ngOnInit(): void {


    let id = this.route.snapshot.paramMap.get('id');
    this.weekNo = Number.parseInt(this.route.snapshot.paramMap.get('week')) || -1;

    this.happinessGroupService.getBest(id).pipe(first()).subscribe(result => {
      if (result) {
        this.best = result;
        this.weeks = this.best.happinessGroup.happinessWeeks.sort((a, b) => a.seq - b.seq);

        if (this.weekNo == -1) {
          var today = new Date();
          this.week = this.weeks.find(week => week.date >= today);

          this.weekNo = this.week ? this.week.seq : 1;
        }

        this.runTypingScripts();
        this.weekPadNo = this.zeroPad(this.weekNo, 2);
      }
    });


  }

  runTypingScripts() {


    this.runTextTypingScript();


  }

  copyAddress() {
    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    if (this.week) {
      dummy.value = `${this.week.address} ${this.week.cityAndZipCode}`;
    } else {
      dummy.value = `${this.best.happinessGroup.leader} ${StringUtils.AddressCszToString(this.best.happinessGroup.serviceAddress)}`;
    }
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
    this.toastrService.success(dummy.value, "複製地址至剪貼簿!");
  }
  zeroPad = (num, places) => String(num).padStart(places, '0');


  private runTextTypingScript() {
    setTimeout(() => {
      let el = document.getElementById("weekPic");
      el.scrollIntoView({ behavior: 'smooth' });
    }, 100);


    var instance = new TypeIt("#typingContent", {
      speed: 125,
      waitUntilVisible: true,
      cursor: false,
      startDelay: 100
    });
    switch (this.weekNo) {
      case 1:
        instance.type(`Hi, <strong>${this.best.name}</strong>,<br>`)
          .type('我們想送你一份禮物，<br>')
          .type('他是人生中最棒的夥伴，<br> ')
          .type('為你帶來超乎想像的幸福感， <br>')
          .type('值得你用8個星期的時間來認識. <br>')
          .type(`${this.best.happinessGroup.name}, 邀你一同了解幸福! `);
        break;
      case 2:
        instance.type(`Hi, <strong>${this.best.name}</strong>,<br>`)
          .options({ speed: 155 }).type('我們想送你一份禮物，').pause(500)
          .options({ speed: 125 }).delete(10)
          .type('你以為我們這麼偷懶 :-)，').break()
          .type('每周的邀請函內容一樣嗎?').break()
          .type('當然不是囉~').break()
          .type('我們可是求新求變，').break()
          .type(`尋找人生新氣象的${this.best.happinessGroup.name}呢~`).break()
          .type('這周想邀請你一起來，').break()
          .type('破除謊言尋找幸福的真相唷~');
        break;
      case 3:
        instance.options({ speed: 70 }).type(`Yo Yo Yo~ <strong>${this.best.name}</strong>,`).break()
          .type('YO COME ON COME ON!').break()
          .type('大家一起說一次蓋世英雄到來~ 恩...').pause(500).break()
          .type('好像走錯場子了 :-)').break()
          .type('這段 NG 剪掉好了').pause(500)
          .options({ speed: 50 }).delete().options({ speed: 90 })
          .type(`Hi, <strong>${this.best.name}</strong>,<br>`)
          .type('你是否有過追星的經驗呢?').break()
          .type('不管是哪個領域的明星，').break()
          .type('想必他們一定是給你帶來過一些幸福的感受，才讓你願意追星的吧!').break()
          .type('這周想邀請你一起來認識一位萬世巨星，').break()
          .type('跟著他一起一路開掛，一生幸福~');
        break;
      case 4:
        instance.type(`Hi, <strong>${this.best.name}</strong>,<br>`)
          .type('你想要的幸福是什麼呢?<br>')
          .type('有想過用什麼樣的方式獲取幸福嗎?<br> ')
          .type('這周的<strong>幸福連線</strong>也許會給你打開一個新的獲取幸福的方式唷!')
        break;
      case 5:
        instance.type(`Hey, <strong>${this.best.name}</strong>,<br>`)
          .type('當有一個人主動來找你<br>')
          .type('說要給你幸福，你是否願意敞開心扉來接這份禮物呢?<br> ')
          .type('邀請你這周一起來看看是什麼樣美好的禮物唷 :-)')
        break;
      case 6:
        instance.type(`Hi, <strong>${this.best.name}</strong>,<br>`)
          .type('你是否曾在世界各地的教堂景點看過十字架呢?<br>')
          .type('你知道它不只是個符號或是裝飾嗎?<br> ')
          .type('這周邀請你一起來探索十字架如何翻轉我們的人生!')
        break;
      case 7:
        instance.type(`Hi, <strong>${this.best.name}</strong>,<br>`)
          .type('你是否曾經感覺生活中充滿無從釋放的壓力與重擔呢?<br>')
          .type('這周想邀請你一起來度過一個輕鬆舒壓的夜晚!')
        break;
      case 8:
        instance.type(`Hi, 親愛的<strong>${this.best.name}</strong>,<br>`)
          .type('經歷了這幾週的幸福之旅，<br>')
          .type('在這週我們想要邀請你來更認識我們充滿愛的 <strong>家</strong>，<br> ')
          .type('和我們度過一段溫馨的家庭聚會時光， <br>')
          .type('感受屬於家的溫暖和幸福！')
        break;

      default:
        instance.type(`Hi, <strong>${this.best.name}</strong>,<br>`)
          .type('我們想送你一份禮物，<br>')
          .type('他是人生中最棒的夥伴，<br> ')
          .type('為你帶來超乎想像的幸福感， <br>')
          .type('值得你用8個星期的時間來認識. <br>')
          .type(`${this.best.happinessGroup.name},邀你一同了解幸福! `);
        break;
    }

    if (this.best.happinessGroup.description) {

      instance
        .break({ delay: 500 })
        .type(`<em>${this.best.happinessGroup.description}</em>`)
    }

    instance
      .exec(async () => {
        setTimeout(() => {

          document.getElementById("addressTypingContainer").scrollIntoView({ behavior: 'smooth' });
          this.runAddressTypingScript();
        }, 500);
      }).go();
  }

  private runAddressTypingScript() {


    let week = this.weeks[this.weekNo - 1];
    new TypeIt('#addressInfoTyping', {
      speed: 125,
      //waitUntilVisible: true,
      cursor: false

    })
      .type('<div class="infoTitle">幸福時刻</div>')
      .pause(500)
      .break()
      .options({ speed: 50 })
      .type(`<span class="typeDate info hightLight">${DateUtils.format(week.date, 'MM/dd/yyyy')}</span>`)
      .break()
      .pause(200)
      .type(`<span class="info">${DateUtils.format(week.date, 'hh:mm aa')}</span>`)
      .break().break()
      .pause(200)
      .options({ speed: 125 })
      .type('<div class="infoTitle">幸福地點</div>')
      .break()
      .pause(200)
      .options({ speed: 50 })
      .type(`<span class="typeAddress info hightLight">${week ? week.address : this.best.happinessGroup.serviceAddress.address}</span>`)
      .break()
      .pause(200)
      .type(`<span class="info">${week ? week.cityAndZipCode : StringUtils.AddressCszToString(this.best.happinessGroup.serviceAddress)}</span>`)
      .break()
      .options({ speed: 125 })
      .exec(async () => {
        this.showCopyBtn = true;
        this.cdr.detectChanges();
      })

      //.type('<span class="infoTitle">開掛玩家歡迎你</span>')
      .go();
  }
}
