import { Component, OnInit, ViewChild } from '@angular/core';
import { IonSlides, ModalController } from '@ionic/angular';
import * as moment from 'moment';
import { ChatPage } from '../chat/chat.page';
import * as faker from 'faker';
import { Router } from '@angular/router';
import { AddPartyPage } from '../add-party/add-party.page';

export type IscoreCard = {
    teamName: string,
    teamLogo: string,
    batting: Array<{
        name: string,
        jersey: number,
        score: number,
        ballsPlayed: number,
        wicketTo?: string,
        boundaries: number,
        sixes: number
    }>,
    bowling: Array<{
        name: string,
        jersey: number,
        runs: number,
        overs: number,
        wickets: number
    }>,
    totalScore: number,
    totalWickets: number,
    overs: number,
    extras: number
}

@Component({
    selector: 'app-live',
    templateUrl: './live.page.html',
    styleUrls: ['./live.page.scss'],
})
export class LivePage implements OnInit {
    @ViewChild('slides') slides: IonSlides;
    
    showScoreCard: boolean = true;
    showFixtures: boolean = false;

    selectedIndex: number = 0;

    slideOpts = {
        slidesPerView: 1.5,
        spaceBetween: 15,
        initialSlide: 0,
        centeredSlides: true,
        // simulateTouch: false,
        // followFinger: false,
    };

    matchStats: {
        stadium: string,
        homeTeam: IscoreCard,
        awayTeam: IscoreCard
    };

    teams = [{
        name: 'RCB',
        image: 'https://i.pinimg.com/originals/4f/f9/99/4ff99925fd51296daf76425b11c04195.jpg'
    }, {
        name: 'MI',
        image: 'assets/logos/mi.svg',
    }, {
        name: 'CSK',
        image: 'https://www.searchpng.com/wp-content/uploads/2019/02/Chennai-Super-Kings-Logo-PNG-Image-.png'
    }];

    stadiums = [{
        name: 'Chinnaswamy',
        sideView: 'https://www.royalchallengers.com/PRRCB01/public/styles/1061x767_landscape/public/2020-04/275679.jpg?h=61617f72&itok=6xKgHpE-',
        topView: 'assets/home-team/stadium-tv.svg',
    }, {
        name: 'IS Bindra',
        sideView: 'https://5.imimg.com/data5/VO/UB/MY-3103550/ae-cricket-stadium-lighting-500x500.jpg',
        topView: 'assets/home-team/stadium-tv.svg'
    }, {
        name: 'Chidambaram Stadium',
        sideView: 'https://sportzwiki.com/wp-content/uploads/2019/03/11.jpg',
        topView: 'assets/home-team/stadium-tv.svg',
    }];

    bookingSeatsData: Array<{
        dateTime: Date,
        staduim: {
            name: string,
            topView: string,
            sideView: string,
        },
        matchType: string,
        matchDetails: {
            home: {
                name: string,
                image: string,
            },
            away: {
                name: string,
                image: string,
            }
        },
        seatsAvailable: Array<{
            stand: 'Grand' | 'Pavilion' | 'First' | 'Second',
            seats: Array<{
                id: number | string,
                price: number
            }>
        }>
    }> = [];

    showAddParty: boolean = false;

    constructor(
        public modalController: ModalController,
        private router: Router
    ) { }

    getFormattedDateTime(dateTime: Date) {
        return moment(dateTime).format('DD MMM');
    }

    getEventDateTime(dateTime: Date) {
        return moment(dateTime).format('ddd, MMM DD YYYY hh:mm a');
    }

    selectIndex() {
        this.slides.getActiveIndex().then((index) => this.selectedIndex = index);
    }

    ngOnInit() {
        for (let i = 0; i < 3; i += 1) {
            this.bookingSeatsData.push({
                dateTime: faker.date.future(),
                staduim : this.stadiums[i],
                matchType: 'T20 League',
                matchDetails: {
                    home: i !==1 ? this.teams[i] : { name: 'KXIP', image: 'assets/home-team/KXIP.svg' },
                    away: i ===1 ? this.teams[i] : { name: 'KXIP', image: 'assets/home-team/KXIP.svg' }
                },
                seatsAvailable: [{
                    stand: 'Grand',
                    seats: [],
                }, {
                    stand: 'Pavilion',
                    seats: [],
                }, {
                    stand: 'First',
                    seats: [],
                }, {
                    stand: 'Second',
                    seats: [],
                }]
            });
        }

        for (let i = 0; i < this.bookingSeatsData.length; i += 1) {
            for (let j = 0; j < this.bookingSeatsData[i].seatsAvailable.length; j += 1) {

                let price = faker.commerce.price();

                let randomNumber = Math.random() * (15 - 0) + 0;

                for (let k = 0; k < randomNumber; k += 1) {
                    this.bookingSeatsData[i].seatsAvailable[j].seats.push({
                        id: this.bookingSeatsData[i].seatsAvailable[j].stand + '##' + k.toString(),
                        price
                    });
                }                    
            }
        }

        this.matchStats = {
            stadium: 'IS Bindra',
            homeTeam: {
                teamName: 'KXIP',
                teamLogo: 'assets/home-team/KXIP.svg',
                batting: [{
                    name: 'V Sehwag',
                    jersey: 44,
                    score: 62,
                    ballsPlayed: 30,
                    wicketTo: 'c Sachin, b D.Steyn',
                    boundaries: 8,
                    sixes: 4,
                }, {
                    name: 'KL Rahul',
                    jersey: 10,
                    score: 85,
                    ballsPlayed: 80,
                    boundaries: 10,
                    sixes: 3,
                }, {
                    name: 'G Maxwell',
                    jersey: 11,
                    score: 10,
                    ballsPlayed: 10,
                    boundaries: 0,
                    sixes: 1,
                }],
                bowling: [{
                    name: 'Harmeet Singh',
                    jersey: 13,
                    runs: 22,
                    overs: 2,
                    wickets: 1
                }, {
                    name: 'Mishra',
                    jersey: 25,
                    runs: 10,
                    overs: 1,
                    wickets: 0
                }],
                totalScore: 157,
                overs: 20,
                extras: 0,
                totalWickets: 1,
            },
            awayTeam : {
                teamName: 'MI',
                teamLogo: 'assets/logos/mi.svg',
                batting: [{
                    name: 'S Tendulkar',
                    jersey: 10,
                    score: 10,
                    ballsPlayed: 12,
                    wicketTo: 'b H.Singh',
                    boundaries: 0,
                    sixes: 1,
                }, {
                    name: 'K Pollard',
                    jersey: 22,
                    score: 44,
                    ballsPlayed: 11,
                    boundaries: 1,
                    sixes: 5,
                }, {
                    name: 'D Bravo',
                    jersey: 38,
                    score: 5,
                    ballsPlayed: 3,
                    boundaries: 1,
                    sixes: 0,
                }],
                bowling: [{
                    name: 'D Steyn',
                    jersey: 12,
                    runs: 55,
                    overs: 4,
                    wickets: 1
                }, {
                    name: 'D Bravo',
                    jersey: 38,
                    runs: 40,
                    overs: 4,
                    wickets: 0
                }, {
                    name: 'S Tendulkar',
                    jersey: 10,
                    runs: 25,
                    overs: 4,
                    wickets: 0
                }, {
                    name: 'Trent Boult',
                    jersey: 17,
                    runs: 37,
                    overs: 4,
                    wickets: 0
                }],
                totalScore: 60,
                overs: 3.2,
                extras: 1,
                totalWickets: 1,
            }
        }
    }

    ionViewDidEnter() {
        if (localStorage.isPartyChatOn === 'no') {
            this.showAddParty = true;
        }
    }

    async presentChatModal() {
        const modal = await this.modalController.create({
          component: ChatPage,
        });
        return await modal.present();
    }

    async presentAddChatModal() {
        const modal = await this.modalController.create({
            component: AddPartyPage,
          });

          modal.onDidDismiss().then((data) => {
              if(data.data.createParty) {
                  this.showAddParty = false;
                  localStorage.isPartyChatOn = 'yes';
              }
          });

          return await modal.present();
    }

    showBookingDetails(matchData) {
        this.router.navigate(['/booking-details' , { matchData: JSON.stringify(matchData) }]);
    }

    showBookingDetailsByIndex() {
        let index = this.selectedIndex;
        this.router.navigate(['/booking-details' , { matchData: JSON.stringify(this.bookingSeatsData[index]) }]);
    }

    showMatchDetails() {
        this.router.navigate(['/match-details', { matchStats: JSON.stringify(this.matchStats) }]);
    }

}
