import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { ToastController } from '@ionic/angular';


type IMember = {
    name: string,
    image: string,
    color: string,
}

@Component({
    selector: 'app-chat',
    templateUrl: './chat.page.html',
    styleUrls: ['./chat.page.scss'],
})
export class ChatPage implements OnInit {
    isPollChecked: boolean = true;
    myMessage: string = '';

    chatData: Array<{
        over: number,
        ballChat: Array<{
            ball: number,
            chat: Array<{
                user: IMember,
                text: string,
            }>,
        }>,
        triviaQuestion: {
            question: string,
            selectedAnswer: number,
            maxUserCount: number,
            options: Array<{
                text: string,
                pollUserCount: string,
            }>,
        }
    }> = [];

    members: Array<IMember> = [];
    myAccount: IMember;

    constructor(
        private modalController: ModalController,
        public toastController: ToastController
    ) { }

    back() {
        this.modalController.dismiss();
    }


    async copyLink() {
        const toast = await this.toastController.create({
            message: 'Copied invitation link!',
            color: 'success',
            mode: 'md',
            duration: 100000,
            position: 'top',
            buttons: [{
                text: 'Ok',
                role: 'cancel',
            }],
          });
          toast.present();
    }

    ngOnInit() {
    }

    scrollToEnd() {
        try {
            let lastOver = this.chatData.length - 1;
            let lastBall = this.chatData[lastOver].ballChat? this.chatData[lastOver].ballChat.length - 1 : null;
            let lastChat = this.chatData[lastOver].ballChat[lastBall].chat ? this.chatData[lastOver].ballChat[lastBall].chat.length - 1 : null;

            document.querySelector('#chat-' + lastOver + '-' + lastBall + '-' + lastChat).scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        } catch {
            document.querySelector('#over-' + (this.chatData.length - 1).toString()).scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    }

    sendMessage() {
        let lastOver = this.chatData.length - 1;
        let lastBall = this.chatData[lastOver].ballChat.length - 1;
        let lastChat = this.chatData[lastOver].ballChat[lastBall].chat.length - 1;

        if (lastChat < 0) {
            lastChat = 0;
        }

        this.chatData[lastOver].ballChat[lastBall].chat.push({
            user: this.myAccount,
            text: this.myMessage
        });

        setTimeout(() => {
            this.scrollToEnd();
            
            this.myMessage = '';
        }, 500);
    }
}
