import {
  ChangeDetectorRef,
  Component,
  Input,
  OnInit,
  ViewEncapsulation,
} from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';

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 { Vendor } from 'app/modules/proto/models/api/vendor_pb';

export enum ComposeMenuType {
  signIn = 'signIn',
  signup = 'signup',
  signOut = 'signOut',
  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;

  liveCasinos!: Vendor[];
  hotelCasinos!: Vendor[];
  slotGames!: Vendor[];

  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 _vendorService: VendorService,
    private __gameService: GameService
  ) {}

  ngOnInit(): void {
    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();
    });
  }
  /**
   * 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;
        return;
        break;
      case ComposeMenuType.signIn:
        selectType = SignInComposeComponent;
        break;
      case ComposeMenuType.signup:
        selectType = SignUpComposeComponent;
        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 async getGameByParentId(
    parenId: number
  ): Promise<ListGamesResponse.Result> {
    return await this.__gameService.listGames(parenId);
  }

  onClickGame(vendor: Vendor): void {
    console.log(vendor.toString());
    this.getGameByParentId(vendor.getId()).then((result) => {
      const gameList = result.getGamesList();

      if (gameList.length === 0) {
        return;
      }
      const game = gameList[0];

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

          window.open(
            r.getUrl(),
            'gamepopup',
            'width=1400, height=900, toolbar=no, menubar=no, scrollbars=no, resizable=yes'
          );
        })
        .catch((e) => {
          console.log('fail', e);
        });
    });
    // window.open(
    //   '/game/?vendor_key=pragmatic_casino&game_key=101',
    //   'gamepopup',
    //   'width=1400, height=900, toolbar=no, menubar=no, scrollbars=no, resizable=yes'
    // );
  }
}
