let u = new URL(location.href)
urlPrivateAPI = u.origin + '/api'

api = new API({
    url: urlPrivateAPI,
    timeout: 10000, // 10 sec
})

Football = 1
Handball = 2
Tennis = 3

OnexbetFootball = 1
OnexbetHandball = 8
OnexbetTennis = 4

onexbetWsURL = 'ws://195.189.227.88:7772/ws'
tipperWsURL = 'ws://195.189.227.88:7768/ws'

document.addEventListener('DOMContentLoaded',  ()=> {
    interesting = new ListModel({
        template: {
            id: 'interestingMatch',
            renders: {
                interestingMatch: (tags, match) => {
                    //console.log('render', match)
                    let radios = new RadioList({
                        container: tags.candidates,
                        templateId: 'candidate-item',
                        setEmptyMessage: 'нет матчей кандидатов'
                    })

                    tags.flashscoreLink.href= `https://www.flashscore.com/match/${match.matchID}/#match-summary/match-summary`

                    tags.search.addEventListener('click', () => {
                        let teamName = tags.teamName.value.trim()

                        if (teamName == '') {
                            return
                        }

                        api.req({
                            func: 'searchMatchCandidatesByTeamName',
                            data: {
                                sportID: Tennis,
                                teamName: teamName,
                            },
                            onError: err => {
                                console.log(err)
                                tags.candidates.textContent = "FUCK: " + err
                            },
                            onSuccess: resp => {
                                tags.submit.disabled = false
                                radios.clear()

                                console.log(resp)
                                if (Array.isArray(resp)) {
                                    resp.forEach(candidate => {
                                        candidate.startTimeStr = moment(candidate.startTime * 1000).format("MMM DD, HH:mm:ss")
                                    })
                                }
                                // show model + form
                                radios.setList(resp)
                            }
                        })
                    })

                    tags.submit.addEventListener('click', () => {
                        //console.log(radios.getSelected())
                        let candidate = radios.getSelected()
                        if (!candidate) {
                            return
                        }

                        let isReverse = tags.isReverse.checked

                        var home, away;

                        if (isReverse) {
                            home = {
                                teamID: match.home.teamID,
                                name: candidate.away
                            }
                            away = {
                                teamID: match.away.teamID,
                                name: candidate.home
                            }
                        } else {
                            home = {
                                teamID: match.home.teamID,
                                name: candidate.home
                            }
                            away = {
                                teamID: match.away.teamID,
                                name: candidate.away
                            }
                        }

                        console.log('home:', home);
                        console.log('away:', away);

                        api.req({
                            func: 'addTeamsAliases',
                            data: {
                                home: home,
                                away: away                                
                            },
                            onError: err => {
                                //tags.candidates.textContent = 'FUCK: ' + err
                                console.log(err)
                            },
                            onSuccess: resp => {
                                //console.log('ok')
                                //tags.identification.click()
                                radios.clear()
                                tags.isReverse.checked = false
                                tags.candidates.textContent = "Алиасы добавлены!"
                                tags.submit.disabled = true
                            }
                        })
                    })

                    tags.identification.addEventListener('click', () => {
                        //console.log('details:', tags.identification.open)
                        //console.log(match)
                        if (tags.identification.open) {
                            //tags.candidates.innerHTML = ''
                        } else {
                            //tags.candidates.innerHTML = ''
                            radios.clear()

                            //radios.setList([
                            //    {home: 'Arsenal', away: 'Mancity', sport: 'Football', champName: 'England. Premier League', startTimeStr: "Oct 06, 12:30:00"},
                            //    {home: 'Arsenal', away: 'Aston villa', sport: 'Football', champName: 'England. Premier League', startTimeStr: "Oct 06, 12:30:00"},
                            //])
                            
                            //tags.candidates.textContent = JSON.stringify(match)
                            
                            api.req({
                                func: 'searchMatchCandidates',
                                data: {
                                    sportID: Tennis,
                                    home: match.home.canonicalName,
                                    away: match.away.canonicalName
                                },
                                onError: err => {
                                    console.log(err)
                                    tags.candidates.textContent = "FUCK: " + err
                                },
                                onSuccess: resp => {
                                    tags.submit.disabled = false
                                    console.log(resp)
                                    if (Array.isArray(resp)) {
                                        resp.forEach(candidate => {
                                            candidate.startTimeStr = moment(candidate.startTime * 1000).format("MMM DD, HH:mm:ss")
                                        })
                                    }
                                    // show model + form
                                    radios.setList(resp)
                                }
                            })  
                                                  
                        }
                    })
                }
            }
        },
        container: 'interesting',
        preFunc: modifyInterestingMatch,
        sort: {
            key: 'startTime',
            reverse: true
        }
    })

    // ONEXBET

    //1xbet
    bookLiveModel = new ListModel({
        template: {
            id: 'liveMatch',
        },
        container: 'book-live',
        preFunc: modifyLiveMatch,
        sort: {
            key: 'startTime',
            reverse: true
        }
    })

    // tips

    tipModel = new ListModel({
        template: {
            id: 'tip',
            renders: {
                tip: (tags, tip) => {
                    //console.log('tags:', tags)
                    //console.log('x:', x)
                    if (tip.status == 1) {
                        tags.matchName.classList.add('profit')
                    } else if (tip.status == 2) {
                        tags.matchName.classList.add('errmsg')
                    } else if (tip.status == 3) {
                        tags.matchName.classList.add('void')
                    }

                    tags.flashscoreLink.href= `https://www.flashscore.com/match/${tip.matchID}/#match-summary/match-summary`

                    tags.setResultLink.addEventListener('click', () => {
                        if (tags.setResultForm.hidden) {
                            let f = new Form({
                                formContainer: tags.setResultForm,
                                schema: [
                                    {
                                        name: 'result',
                                        type: 'line',
                                        label: 'Результат',
                                        comment: 'например, 1й тайм: 1:1'
                                    },
                                    {
                                        name: 'status',
                                        type: 'radios',
                                        label: ' ',
                                        getName: x => x.name,
                                        data: [
                                            {name: 'Выигрыш', status: 1},
                                            {name: 'Проигрыш', status: 2},
                                            {name: 'Возврат', status: 3},
                                        ]
                                    },
                                ]
                            })

                            f.onSubmit((obj) => {
                                obj.tipID = tip.tipID
                                //console.log(obj)
                                api.req({
                                    func: 'setTipResult',
                                    data: obj,
                                    onError: err => {
                                        f.showError(err)
                                    },
                                    onSuccess: () => {
                                        // Перезагружаем список
                                        api.req({
                                            func: 'listSportTips',
                                            data: Tennis,
                                            onSuccess: resp => {
                                                tipModel.setList(resp)
                                            }
                                        })
                                    }
                                })
                            })

                            f.init()

                            tags.setResultForm.hidden = false
                        } else {
                            tags.setResultForm.hidden = true                            
                        }
                    })
                }
            }
        },
        container: 'tips',
        preFunc: modifyTip,
        sort: {
            key: 'tipTime',
            //reverse: true
        }
    })


    // strategies

    strategiesModel = new ListModel({
        template: {
            id: 'strategy',
        },
        container: 'strategies',
        preFunc: (r) => {
            r.roi = Math.round(r.roi*100)/100
            r.profit = Math.round(r.profit*100)/100
            r.drawdown = Math.round(r.drawdown*100)/100
            r.accuracy = Math.round(r.accuracy*100)/100
        },
    })

    totalsModel = new ListModel({
        template: {
            id: 'total',
        },
        container: 'totals',
        preFunc: (r) => {
            r.roi = Math.round(r.roi*100)/100
            r.profit = Math.round(r.profit*100)/100
            r.drawdown = Math.round(r.drawdown*100)/100
            r.accuracy = Math.round(r.accuracy*100)/100
        },
    })

    

    let onexbetWs = new WebsocketClient({
        url: onexbetWsURL
    })
  
    onexbetWs.handle('liveMatches', resp => {
        //console.log('liveMatches:', resp)
        
        if (resp.sportID == OnexbetTennis) {
            if (Array.isArray(resp.matches)) {
                bookLiveModel.setList(resp.matches)

                resp.matches.forEach(match => {
                    //console.log('partialUpdateBy')
                    interesting.partialUpdateBy(
                        // update func
                        (tags, obj) => {
                            //console.log('SCORE: ', tennisScoreToString(match.scoreByPeriods))
                            tags.livescore.textContent = tennisScoreToString(match.scoreByPeriods)
                            tags.livescore.hidden = false
                        },
                        // key func
                        (obj) => {
                            //console.log('COMPARE:', obj.onexbetMatchID, '=', match.matchID)
                            if (obj.onexbetMatchID == match.matchID) {
                                return true
                            } 
                        }
                    )
                })
            }
        }
    })

    onexbetWs.handle('teamLiveMatchData', resp => {
        //console.log('teamLiveMatchData:', resp)
    })
   

    // tipper
    let tipperWs = new WebsocketClient({
        url: tipperWsURL
    })

    tipperWs.onConnected = () => {
        tipperWs.send('subscribe', {channels: ['tennis']})
    }

    tipperWs.handle('teamMatches', resp => {        
        //console.log('reports:', resp)
        if (resp.sportID == Tennis) {            
            if (Array.isArray(resp.matches)) {
                //console.log('set interesting:', resp.matches)
                interesting.setList(resp.matches)
            }
        }
    })

    tipperWs.handle('tipsChanged', resp => {
        //console.log('tip:', resp)
        
        //tipModel.add(resp)

        api.req({
            func: 'listSportTips',
            data: Tennis,
            onSuccess: resp => {
                tipModel.setList(resp)
            }
        })
    
        api.req({
            func: 'listStrategiesReports',
            data: Tennis,
            onSuccess: resp => {
                strategiesModel.setList(filterStrategies(resp))
                showTotal(resp)
            }
        })
    })

    tipperWs.handle('whyNot', resp => {        
        //console.log('whyNot:', resp.matchID, resp.comment)
        interesting.partialUpdateBy(
        (tags, obj) => {
            tags.comment.innerHTML = resp.comment
            tags.time.textContent = resp.time
            tags.score.textContent = `${resp.homeGoals} - ${resp.awayGoals}`
            //tags.gamePace.textContent = resp.gamePace
            //tags.gamePaceFrame.textContent = resp.gamePaceFrame + 1
        },
        (obj) => {
            if (obj.matchID == resp.matchID) {
                return true
            }
        })
    })

    tipperWs.handle('inplayStatusChanged', resp => {        
        //console.log('inplayStatusChanged:', resp)
        interesting.partialUpdateBy(
        (tags, obj) => {
            if (resp.isInplay) {
                tags.isInplay.textContent = 'inplay'
            } else {
                tags.isInplay.textContent = ''
            }

            if (resp.isLinkedToOnexbet) {
                tags.isLinked.textContent = 'linked to 1xBet'
            } else {
                tags.isLinked.textContent = ''
            }
        },
        (obj) => {
            if (obj.matchID == resp.matchID) {
                return true
            }
        })
    })


/*
    ws.handle('footballMatchReports', resp => {
        console.log('reports:', resp)
        updateChamp(resp)        
    })
*/

    api.req({
        func: 'listSportTips',
        data: Tennis,
        onSuccess: resp => {
            tipModel.setList(resp)
        }
    })

    api.req({
        func: 'listStrategiesReports',
        data: Tennis,
        onSuccess: resp => {
            strategiesModel.setList(filterStrategies(resp))
            showTotal(resp)
        }
    })

    onexbetWs.connect()
    tipperWs.connect()

})


function showTotal(reports) {
    // 1,2,3
    let allChampsTotal = {
        name: 'Все чемпионаты',
        wonTips: 0,
        lostTips: 0,
        accuracy: 0, 
        profit: 0,
        turnover: 0,
        roi: 0
    }
/*
    let topChampsTotal = {
        name: 'Топ чемпионаты',
        wonTips: 0,
        lostTips: 0,
        accuracy: 0, 
        profit: 0,
        turnover: 0,
        roi: 0
    }

    let myTotal = {
        name: 'Алгоритмы от Программиста',
        wonTips: 0,
        lostTips: 0,
        accuracy: 0, 
        profit: 0,
        turnover: 0,
        roi: 0
    }
*/
    let m = new Map()
    
    m.set(15, allChampsTotal)
    m.set(16, allChampsTotal)
    m.set(17, allChampsTotal)
    m.set(18, allChampsTotal)
    
    if (Array.isArray(reports)) {
        reports.forEach(r => {
            let total = m.get(r.strategyID)
            if (!total) {
                return
            }

            total.wonTips += r.wonTips
            total.lostTips += r.lostTips
            total.profit += r.profit
            total.turnover += r.turnover
        })
    }

    clacROIandAccuracy(allChampsTotal)
    //clacROIandAccuracy(topChampsTotal)
    //clacROIandAccuracy(myTotal)
    

    //totalsModel.setList([allChampsTotal, topChampsTotal, myTotal])
    totalsModel.setList([allChampsTotal])

    //document.getElementById('total').textContent = 'Общий итог: ' + total + ' грн'
}

function clacROIandAccuracy(total) {
    total.roi = (total.profit * 100) / total.turnover
    total.accuracy = (total.wonTips * 100) / (total.wonTips + total.lostTips)

    //total.roi = Math.round(total.roi*100)/100
    //total.accuracy = Math.round(total.accuracy*100)/100
}




function modifyReport(report) {
    report.match = `${report.home.canonicalName} - ${report.away.canonicalName}`
    report.msg = JSON.stringify(report, null, 3)
}


function modifyInterestingMatch(report) {
    //console.log(report)

    report.champName = `${report.zone.name}. ${report.champ.name}`
    report.startTimeStr = moment(report.startTime * 1000).format("MMM DD, HH:mm:ss")
    let home = report.home.canonicalName
    if (!report.home.wasLinked) {
        home = '*' + home
    }
    let away = report.away.canonicalName
    if (!report.away.wasLinked) {
        away = '*' + away
    }
    report.match = `${home} - ${away}`
    if (report.isLinkedToOnexbet) {
        report.isLinked = 'linked to 1xBet'
    }
    if (report.isInplay) {
        report.isInplay = 'inplay'
    } else {
        report.isInplay = ''
    }
    report.notes = JSON.stringify(report, null, 3)

    
}


function modifyLiveMatch(report) {
    if (!report.match) {
        report.champName = `${report.sportName}. ${report.champName}`
    } 
    report.startTimeStr = moment(report.startTime * 1000).format("MMM DD, HH:mm:ss")
    report.match = `${report.home} - ${report.away}`
}

function modifyTip(report) {
    report.msg = JSON.stringify(report, null, 3)
}

function filterStrategies(src) {
    let list = []
    if (Array.isArray(src)) {
        src.forEach(s => {
            list.push(s)
        })
    }
    return list
}

function tennisScoreToString(scoreByPeriods) {
    if (!scoreByPeriods) {
        return ''
    }

    let list = []

    for (var i=1; i <= 5; i++) {
        let p = scoreByPeriods[i]
        if (p) {
            list.push(`${p.home}:${p.away}`)
        } else {
            break
        }
    }
    
    return list.join(' ')
}