import {
  ChangeDetectorRef,
  Component,
  Input,
  OnInit,
  ViewEncapsulation,
} from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { FuseConfirmationService } from '@fuse/services/confirmation';
import { AuthService } from 'app/core/auth/auth.service';

import { CompComposeComponent } from 'app/modules/beteran/compose/compose/comp-compose.component';
import { CustomerComposeComponent } from 'app/modules/beteran/compose/compose/customer-compose.component';
import { DepositComposeComponent } from 'app/modules/beteran/compose/compose/deposit-compose.component';
import { DepositHistoryComposeComponent } from 'app/modules/beteran/compose/compose/deposit-history-compose.component';
import { NoticeComposeComponent } from 'app/modules/beteran/compose/compose/notice-compose.component';
import { SignInComposeComponent } from 'app/modules/beteran/compose/compose/sign-in-compose.component';
import { SignUpComposeComponent } from 'app/modules/beteran/compose/compose/sign-up-compose.component';
import { WithdrawComposeComponent } from 'app/modules/beteran/compose/compose/withdraw-compose.component';
import { WithdrawHistoryComposeComponent } from 'app/modules/beteran/compose/compose/withdraw-history-compose.component';
import { GameService } from 'app/modules/polyglot/api/services/game.service';
import { VendorService } from 'app/modules/polyglot/api/services/vendor.service';
import { ListGamesResponse } from 'app/modules/proto/c2se/api/game_pb';
import { Game } from 'app/modules/proto/models/api/game_pb';
import { Vendor } from 'app/modules/proto/models/api/vendor_pb';
import { environment } from 'environments/environment';
import { ModifyMemberComposeComponent } from '../compose/compose/modify-member-compose.component';
import { SlotGameComposeComponent } from '../compose/compose/slot-game-compose.component';
import { MessageComposeComponent } from '../compose/compose/message-compose.component';
import { MemberService } from 'app/modules/polyglot/member/services/member.service';
import { MemberModel } from 'app/modules/proto/models/member_pb';

export enum ComposeMenuType {
  signIn = 'SignIn',
  signup = 'Signup',
  signOut = 'SignOut',
  modifyMember = 'ModifyMember',
  deposit = 'Deposit',
  withdraw = 'Withdraw',
  notice = 'Notice',
  comp = 'Comp',
  customer = 'Customer',
  depositHistory = 'DepositHistory',
  withdrawHistory = 'WithdrawHistory',
}

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  encapsulation: ViewEncapsulation.None,
})
export class HomeComponent implements OnInit {
  @Input()
  loggedIn: boolean = false;

  composeMenuType = ComposeMenuType;

  configForm!: FormGroup;

  liveCasinos!: Vendor[];
  hotelCasinos!: Vendor[];
  slotGames!: Vendor[];
  member!: MemberModel | undefined;

  data = {
    schedule: {
      today: [
        {
          title: '계좌 등록 안내',
          time: '2022-06-08',
        },
        {
          title: '오토프로그램 이용 안냐',
          time: '2022-06-08',
        },
        {
          title: '입출금 규정 안내',
          time: '2022-06-08',
        },
        {
          title: '원피(가상계좌)사용 안내',
          time: '2022-06-08',
        },
        {
          title: '입금문의 안내(필독)',
          time: '2022-06-08',
        },
      ],
    },
  };
  /**
   * Constructor
   */
  constructor(
    private _changeDetectorRef: ChangeDetectorRef,
    private _router: Router,
    private _matDialog: MatDialog,
    private _formBuilder: FormBuilder,
    private _fuseConfirmationService: FuseConfirmationService,
    private _vendorService: VendorService,
    private _gameService: GameService,
    private _memberService: MemberService,
    private _authService: AuthService
  ) {}

  ngOnInit(): void {
    if (!!this.loggedIn) {
      const memberInfo = this._authService.memberInfo;
      this._memberService
        .getMemberByUsername(memberInfo.username)
        .then((res) => (this.member = res.getMember()));
    }
    this._vendorService.listVendors().then((result) => {
      this.liveCasinos = result
        .getVendorsList()
        .filter((v) => v.getCategory() === 'casino');

      this.hotelCasinos = result
        .getVendorsList()
        .filter((v) => v.getCategory() === 'casino');
      this.slotGames = result
        .getVendorsList()
        .filter((v) => v.getCategory() === 'slot');

      this._changeDetectorRef.markForCheck();
    });

    this.configForm = this._formBuilder.group({
      title: '알림',
      message: '로그아웃 하시겠습니까?',
      icon: this._formBuilder.group({
        show: true,
        name: 'heroicons_outline:exclamation',
        color: 'warn',
      }),
      actions: this._formBuilder.group({
        confirm: this._formBuilder.group({
          show: true,
          label: '확인',
          color: 'warn',
        }),
        cancel: this._formBuilder.group({
          show: true,
          label: '취소',
        }),
      }),
      dismissible: true,
    });
  }
  /**
   * Track by function for ngFor loops
   *
   * @param index
   * @param item
   */
  trackByFn(index: number, item: any): any {
    return item.id || index;
  }

  /**
   * @param composeMenuType
   */
  __onClickCompose(composeMenuType: ComposeMenuType): void {
    let selectType: any;

    if (
      !this.loggedIn &&
      composeMenuType !== ComposeMenuType.signIn &&
      composeMenuType !== ComposeMenuType.signup
    ) {
      alert('로그인 후 이용해주세요.');
      return;
    }
    switch (composeMenuType) {
      case ComposeMenuType.signOut:
        // selectType = SignInComposeComponent;
        this.checkSignout();

        return;
        break;
      case ComposeMenuType.signIn:
        selectType = SignInComposeComponent;
        break;
      case ComposeMenuType.signup:
        selectType = SignUpComposeComponent;
        break;
      case ComposeMenuType.modifyMember:
        selectType = ModifyMemberComposeComponent;
        break;
      case ComposeMenuType.deposit:
        selectType = DepositComposeComponent;
        break;
      case ComposeMenuType.withdraw:
        selectType = WithdrawComposeComponent;
        break;
      case ComposeMenuType.notice:
        selectType = NoticeComposeComponent;
        break;
      case ComposeMenuType.comp:
        selectType = CompComposeComponent;
        break;
      case ComposeMenuType.customer:
        selectType = CustomerComposeComponent;
        break;
      case ComposeMenuType.depositHistory:
        selectType = DepositHistoryComposeComponent;
        break;
      case ComposeMenuType.withdrawHistory:
        selectType = WithdrawHistoryComposeComponent;
        break;
    }

    const dialogRef = this._matDialog.open(selectType);

    dialogRef.afterClosed().subscribe((result) => {
      if (ComposeMenuType.signIn === composeMenuType && !!result.choice) {
        this._router.navigate(['game']);
      }
      console.log('Compose dialog was closed!');
    });
  }

  private checkSignout(): void {
    const dialogRef = this._fuseConfirmationService.open(this.configForm.value);

    // Subscribe to afterClosed from the dialog reference
    dialogRef.afterClosed().subscribe((result) => {
      if (result === 'confirmed') {
        this._authService
          .signOut()
          .subscribe(() => this._router.navigate(['main']));
      }
    });
  }
  private async getGameByParentId(
    parenId: number
  ): Promise<ListGamesResponse.Result> {
    return await this._gameService.listGames(parenId);
  }

  private openGameWindow(url: string): void {
    window.open(
      url,
      'gamepopup',
      'width=1400, height=900, toolbar=no, menubar=no, scrollbars=no, resizable=yes'
    );
  }
  private showSlotDialog(vendor: Vendor, gameList: Game[]): void {
    const dialogRef = this._matDialog.open(SlotGameComposeComponent, {
      data: {
        vendor,
        gameList,
      },
    });

    dialogRef.afterClosed().subscribe((result) => {
      console.log('Slot game Compose dialog was closed!');
    });
  }

  onClickGame(vendor: Vendor, type: number): void {
    console.log(vendor.toString());

    this.getGameByParentId(vendor.getId()).then((result) => {
      const gameList = result.getGamesList();
      if (gameList.length === 0) {
        return;
      }
      if (type === 2) {
        this.showSlotDialog(vendor, gameList);
        return;
      }

      let gameKey = '';
      const constKey = environment.constants.casinoGameKey;

      switch (vendor.getKey()) {
        case 'evolution_casino':
          gameKey = constKey.evolution;
          break;
        case 'pragmatic_casino':
          gameKey = constKey.pragmatic;
          break;
        case 'cq9_casino':
          gameKey = constKey.cq9;
          break;
        case 'skywind_casino':
          gameKey = constKey.skywind;
          break;
        case 'wm_casino':
          gameKey = constKey.wm;
          break;
        case 'duwon_casino':
          gameKey = constKey.duwon;
          break;
        case 'bg_casino':
          gameKey = constKey.bg;
          break;
        case 'oriental_casino':
          gameKey = constKey.oriental;
          break;
        default:
          break;
      }

      if (gameKey === '') {
        gameKey = gameList[0].getKey();
      }

      let r = this._gameService
        .getGameUrl(vendor.getKey(), gameKey)
        .then((r) => {
          console.log('success', r.getUrl());

          this.openGameWindow(r.getUrl());
        })
        .catch((e) => {
          console.log('fail', e);
        });
    });
  }

  __onClickMessage(event: MouseEvent): void {
    const dialogRef = this._matDialog.open(MessageComposeComponent, {
      data: { price: '', memo: '' },
    });
  }
}
