import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import * as faker from 'faker';
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() {

        let myAccountIndex = Math.floor(Math.random() * 11);

        for (let i = 0; i < 12; i += 1) {
            this.members.push({
                name:  myAccountIndex === i ? 'You' : faker.name.findName(),
                image: 'assets/home-team/roster/' + (i + 1) + '.png',
                color: faker.vehicle.color()
            });
        }

        this.myAccount = this.members[myAccountIndex];

        
        for (let i = 0; i < 2; i += 1) {
            let options = [];
            
            for (let j = 0; j < 4; j += 1) {
                options.push({
                    text: faker.lorem.word(),
                    pollUserCount: faker.random.number()
                });
            }            

            let ballChat = [];

            for (let balls = 0; balls < 6; balls += 1) {
                let randomNumber = Math.floor(Math.random() * 3) + 1;
                let chat = [];

                for (let k = 0; k < randomNumber; k += 1) {
                    let randomMemberIndex = Math.floor(Math.random() * 3);
                    chat.push({
                        user: this.members[randomMemberIndex],
                        text: faker.lorem.sentence(),
                        time: faker.time.recent(),
                    });
                }

                ballChat.push({
                    ball: balls,
                    chat: chat
                });
            }

            this.chatData.push({
                over: i,
                ballChat: ballChat,
                triviaQuestion: {
                    question: faker.lorem.sentence(),
                    maxUserCount: Math.max.apply(Math, options.map(function(o) { return o.pollUserCount; })),
                    options: options,
                    selectedAnswer: Math.floor(Math.random() * 4),
                }
            });
        }

        setTimeout(() => {
            let options = [];

            for (let j = 0; j < 4; j += 1) {
                options.push({
                    text: faker.lorem.word(),
                    pollUserCount: faker.random.number()
                });
            }

            this.chatData.push({
                over: this.chatData.length - 1,
                ballChat: [{
                    ball: 0,
                    chat: [],
                }],
                triviaQuestion: {
                    question: faker.lorem.sentence(),
                    maxUserCount: Math.max.apply(Math, options.map(function(o) { return o.pollUserCount; })),
                    options: options,
                    selectedAnswer: null,
                }
            });

            setTimeout(() => {
                this.scrollToEnd();
            }, 1000);
            

        }, 200);

    }

    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);
    }
}
