import { Component, OnInit, ViewChild } from '@angular/core';
import { IonSlides } from '@ionic/angular';
import * as moment from 'moment';
import { Router } from '@angular/router';
import { MatchService } from '../services/match.service';
import { ToastService } from '../services/toast.service';

export type IMatch = {
    match_date: string,
    match_id: string,
    match_time: string,
    team_a: string,
    team_a_id: string,
    team_a_short: string,
    team_b: string,
    team_b_id: string,
    team_b_short: string,
    venue: string,
    venue_id: string,
};


interface RawMatchDetailMatchInfo {
    Livecoverage: string;
    Id: string;
    Code: string;
    League: string;
    League_Id: string;
    Number: string;
    Type: string;
    Date: string;
    Time: string;
    Offset: string;
    Group: string;
    Coverage_level_id: string;
    Coverage_level: string;
    Match_ordinal: string;
    Daynight: string;
    Comp_type_id: string;
    End_date: string;
    End_time: string;
}

interface RawMatchDetailsSeries {
    Id: string;
    Name: string;
    Series_short_display_name: string;
    Series_start_date: string;
    Series_end_date: string;
    Series_type: string;
    Status: string;
    Tour: string;
    Tour_Name: string;
}

interface RawMatchDetails {
    Team_Home: string;
    Team_Away: string;

    Match: RawMatchDetailMatchInfo;
    Series: RawMatchDetailsSeries;
    
    Venue: {
        Id: string;
        Name: string;
    };

    Tosswonby: string;
    Toss_elected_to: string;
    Status: string;
    Status_Id: string;

    // Info during or after completion of match

    Result?: string;
    Winningteam?: string;
    Winmargin?: string;
    Equation?: string;
}

interface RawMatchPlayerBatting {
    Style: string;
    Average: string;
    Strikerate: string;
    Runs: string;
}

interface RawMatchPlayerBowling {
    Style: string;
    Average: string;
    Economyrate: string;
    Wickets: string;
}

interface RawMatchPlayerDetails {
    Position: string;
    Name_Full: string;
    Skill: string;
    Matches: string;
    Batting: RawMatchPlayerBatting;
    Bowling: RawMatchPlayerBowling;
}

interface RawMatchPlayersDetails {
    [player_id: string]: RawMatchPlayerDetails;
}

interface RawMatchTeamDetails {
    Name_Full: string;
    Name_Short: string;
    Players: RawMatchPlayersDetails;
}

interface RawMatchTeamsDetails {
    [team_id: string]: RawMatchTeamDetails;
}

interface RawMatchInningsBatsman {
    Batsman: string;
    Runs: string;
    Balls: string;
    Fours: string;
    Sixes: string;
    Dots: string;
    Strikerate: string;
    Dismissal: string;
    Howout: string;
    Bowler: string;
    Fielder: string;
    Number: number;
    DismissalType: string;
    DismissalId: string;
}

interface RawMatchInningsBowler {
    Bowler: string;
    Overs: string;
    Maidens: string;
    Runs: string;
    Wickets: string;
    Economyrate: string;
    Noballs: string;
    Wides: string;
    Dots: string;
    Number: number;
}

interface RawMatchInningsCurrentPartnershipBatsman {
    Batsman: string;
    Runs: string;
    Balls: string;
}

interface RawMatchInningsPartnership {
    Runs: string,
    Balls: string,
    Batsmen: Array<RawMatchInningsCurrentPartnershipBatsman>;
    ForWicket: number;
}

interface RawMatchInningsFallOfWicket {
    Batsman: string;
    Score: string;
    Overs: string;
    Wicket_No: string;
    Review_status_id: string;
}

interface RawMatchInnings {
    Number: string;
    Battingteam: string;
    Bowlingteam: string;
    Total: string;
    Wickets: string;
    Overs: string;
    Runrate: string;
    Byes: string;
    Legbyes: string;
    Wides: string;
    Noballs: string;
    Penalty: string;
    AllottedOvers: string;

    Batsmen: Array<RawMatchInningsBatsman>;
    Partnership_Current: RawMatchInningsPartnership;
    Bowlers: Array<RawMatchInningsBowler>;
    FallofWickets: Array<RawMatchInningsFallOfWicket>;
    Partnerships: Array<RawMatchInningsPartnership>;
    
    OverNo: string;
    BallNo: string;
}

export interface RawMatchData {
    Timestamp: string;
    Matchdetail: RawMatchDetails;
    Teams: RawMatchTeamsDetails;
    
    // Info during or after completion of match
    Innings?: Array<RawMatchInnings>;
}


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

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

    fixtures: Array<IMatch> = [];
    currentMatch: RawMatchData;

    constructor(
        private router: Router,
        private matchService: MatchService,
        private toastService: ToastService
    ) { }

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

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

    ngOnInit() {
        
    }

    ionViewDidEnter() {
        this.matchService.getFixtures().then((data: Array<IMatch>) => {
            this.fixtures = data;

            let current_date = moment(),
            tempDiffDays = [],
            closestDay = null,
            closestIndex = null,
            closestMatch: IMatch;

            for (let i = 0; i < this.fixtures.length; i += 1) {
                tempDiffDays.push(current_date.diff(moment(this.fixtures[i].match_date + ' ' + this.fixtures[i].match_time), 'days'));
            }

            closestDay = tempDiffDays.reduce((prev, curr) => {
                return (Math.abs(curr - 0) < Math.abs(prev - 0) ? curr : prev);
            });

            closestIndex = tempDiffDays.findIndex((days) => {
                return days === closestDay;
            });

            closestMatch = this.fixtures[closestIndex];
            
            this.slides.slideTo(closestIndex);

            if (closestMatch) {
                this.matchService.getMatchDetails(closestMatch.match_id).then((match_data: RawMatchData) => {
                    this.currentMatch = match_data;
                });
            }            

        }, (err) => {
            console.log(err);
            this.toastService.presentToastWithOptions("Failed to get Fixtures", "danger");
        });
    }

    showMatchDetails(matchId?: string | number) {
        this.router.navigate(['/match-details', { match_id: matchId ? matchId : this.currentMatch.Matchdetail.Match.Id }]);
    }

}
