import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { MatchService } from '../services/match.service';
import { ToastService } from '../services/toast.service';
import { RawMatchData } from '../live/live.page';
import { SocialSharing } from '@ionic-native/social-sharing/ngx';

interface RawCommentaryForBall {
    Over: string;
    Id: string;
    Runs: string;
    ZAD: string;
    Detail: string;
    Isball: boolean;
    Bowler: string;
    Bowler_Name: string;
    Batsman: string;
    Batsman_Name: string;
    Batsman_Style: string;
    Commentary: string;
    Timestamp: string;
    Non_Striker: string;
    Non_Striker_Name: string;
    Score: string;
    Batsman_Runs: string;
    Bowler_Conceded_Runs: string;
    Extras_Runs: string;
    Ball_Speed: string;
}

// 200556

export interface RawCommentary {
    InningNo: string;
    BattingTeam_Id: string;
    BattingTeam: string;
    BowlingTeam_Id: string;
    BowlingTeam: string;
    GameCode: string;
    MatchId: string;
    Timestamp: string;

    Commentary: Array<RawCommentaryForBall>;
}


@Component({
    selector: 'app-match-details',
    templateUrl: './match-details.page.html',
    styleUrls: ['./match-details.page.scss'],
})
export class MatchDetailsPage implements OnInit {
    isPlayerSelected: boolean = false;
    isHomeTeamSelected: boolean = true;

    selectedSegment: 'MATCH' | 'SCORE' = 'MATCH';
    selectedRoster: 'LIVE' | 'HOME' | 'AWAY' = 'LIVE';

    currentMatch: RawMatchData;

    selectedPlayer: string = '';

    commentaryList: Array<RawCommentary> = [];

    commentaryInterval: any;

    constructor(
        private location: Location,
        private route: ActivatedRoute,
        private matchService: MatchService,
        private toastService: ToastService,
        private socialSharing: SocialSharing
    ) { }

    shareMatchDetails() {
        console.log("Sharing match details...");
        let message: string = '';

        if (this.currentMatch.Innings) {
            this.currentMatch.Innings.forEach(inning => {
                message += this.currentMatch.Teams[inning.Battingteam].Name_Short + ' ' + inning.Total + '/' + inning.Wickets + '(' + inning.Overs + ')' + '\n';
            });
        } else {
            message = 'Match to start on, ' + this.currentMatch.Matchdetail.Match.Date + ' @' + this.currentMatch.Matchdetail.Match.Time + '\n' + this.currentMatch.Teams[this.currentMatch.Matchdetail.Team_Home].Name_Short + ' v/s ' + this.currentMatch.Teams[this.currentMatch.Matchdetail.Team_Away].Name_Short;
        }

        this.socialSharing.share(message);
    }

    ngOnInit() {
        let match_id = JSON.parse(this.route.snapshot.paramMap.get('match_id'));
        
        this.matchService.getMatchDetails(match_id).then((match_data: RawMatchData) => {
            this.currentMatch = match_data;
        });

        this.callCommentary(match_id);

        this.commentaryInterval = setInterval(() => {
            this.callCommentary(match_id);
        }, 30000);
    }

    callCommentary(match_id) {
        this.matchService.getCommentary(match_id).then((data: Array<RawCommentary>) => {
            this.commentaryList = data;            
        }, (err) => {
            console.log(err);
            this.toastService.presentToastWithOptions("Failed to fetch Commentary", "danger");
        });
    }

    ngOnDestroy() {
        clearInterval(this.commentaryInterval);
    }

    getReversedArray(array: Array<RawCommentary>) {
        return array.reverse();
    }

    back() {
        this.location.back();
    }

    selectPlayerDetails(playerId: string) {
        this.selectedPlayer = playerId;
        this.isPlayerSelected = true;
    }

    limitDecimals(value: number) {
        return value.toPrecision(2);
    }

    getArrayOfPlayers(players) {
        return Object.keys(players);
    }

}
