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

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

Football = 1
Handball = 2

flashscoreWsURL = 'ws://195.189.227.88:5757/ws'
onexbetWsURL = 'ws://195.189.227.88:5758/ws'
tipperWsURL = 'ws://195.189.227.88:5759/ws'

document.addEventListener('DOMContentLoaded',  ()=> {
    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
        },
    })
    
    spa = new ListModel({
        template: {
            id: 'report',
        },
        container: 'spa',
        preFunc: modifyReport,
    })

    spa2 = new ListModel({
        template: {
            id: 'report',
        },
        container: 'spa2',
        preFunc: modifyReport,
    })


    eng = new ListModel({
        template: {
            id: 'report',
        },
        container: 'eng',
        preFunc: modifyReport,
    })


    eng2 = new ListModel({
        template: {
            id: 'report',
        },
        container: 'eng2',
        preFunc: modifyReport,
    })

    ger = new ListModel({
        template: {
            id: 'report',
        },
        container: 'ger',
        preFunc: modifyReport,
    })

    ita = new ListModel({
        template: {
            id: 'report',
        },
        container: 'ita',
        preFunc: modifyReport,
    })

    ita2 = new ListModel({
        template: {
            id: 'report',
        },
        container: 'ita2',
        preFunc: modifyReport,
    })

    por = new ListModel({
        template: {
            id: 'report',
        },
        container: 'por',
        preFunc: modifyReport,
    })


    ukr = new ListModel({
        template: {
            id: 'report',
        },
        container: 'ukr',
        preFunc: modifyReport,
    })


    swi = new ListModel({
        template: {
            id: 'report',
        },
        container: 'swi',
        preFunc: modifyReport,
    })


    tur = new ListModel({
        template: {
            id: 'report',
        },
        container: 'tur',
        preFunc: modifyReport,
    })


    rus = new ListModel({
        template: {
            id: 'report',
        },
        container: 'rus',
        preFunc: modifyReport,
    })

    rom = new ListModel({
        template: {
            id: 'report',
        },
        container: 'rom',
        preFunc: modifyReport,
    })

    mon = new ListModel({
        template: {
            id: 'report',
        },
        container: 'mon',
        preFunc: modifyReport,
    })


    bel = new ListModel({
        template: {
            id: 'report',
        },
        container: 'bel',
        preFunc: modifyReport,
    })

    gre = new ListModel({
        template: {
            id: 'report',
        },
        container: 'gre',
        preFunc: modifyReport,
    })


    che = new ListModel({
        template: {
            id: 'report',
        },
        container: 'che',
        preFunc: modifyReport,
    })


    cro = new ListModel({
        template: {
            id: 'report',
        },
        container: 'cro',
        preFunc: modifyReport,
    })


    den = new ListModel({
        template: {
            id: 'report',
        },
        container: 'den',
        preFunc: modifyReport,
    })

/*
    = new ListModel({
        template: {
            id: 'report',
        },
        container: '',
        preFunc: modifyReport,
    })


    = new ListModel({
        template: {
            id: 'report',
        },
        container: '',
        preFunc: modifyReport,
    })


    = new ListModel({
        template: {
            id: 'report',
        },
        container: '',
        preFunc: modifyReport,
    })


    = new ListModel({
        template: {
            id: 'report',
        },
        container: '',
        preFunc: modifyReport,
    })
    */


    //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')
                    }
                }
            }
        },
        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
        },
    })


    // flashscore
    let ws = new WebsocketClient({
        //url: 'ws://localhost:5757/ws'
        //url: 'ws://167.99.157.181:5757/ws'
        url: flashscoreWsURL
    })

    //ws.onconnected = 

    ws.handle('footballChamps', resp => {
        console.log('champs:', resp)
        if (Array.isArray(resp.Champs)) {
            //console.log('array')
            resp.Champs.forEach(champ => {
                console.log(champ)
                updateChamp(champ)
            })
        }
    })

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

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

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

                        if (teamName == '') {
                            return
                        }

                        api.req({
                            func: 'searchMatchCandidatesByTeamName',
                            data: {
                                sportID: Football,
                                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
                        }
                        api.req({
                            func: 'addTeamsAliases',
                            data: {
                                home: {
                                    teamID: match.home.teamID,
                                    name: candidate.home
                                },
                                away: {
                                    teamID: match.away.teamID,
                                    name: candidate.away
                                }
                                
                            },
                            onError: err => {
                                //tags.candidates.textContent = 'FUCK: ' + err
                                console.log(err)
                            },
                            onSuccess: resp => {
                                //console.log('ok')
                                //tags.identification.click()
                                radios.clear()
                                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: Football,
                                    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
        }
    })

    // 1xbet
    let onexbetWs = new WebsocketClient({
        //url: 'ws://localhost:5758/ws'
        //url: 'ws://167.99.157.181:5758/ws'
        url: onexbetWsURL
    })
  
    onexbetWs.handle('liveMatches', resp => {
        console.log('liveMatches:', resp)
        
        if (Array.isArray(resp.matches)) {
            bookLiveModel.setList(resp.matches)
        }        
    })

    onexbetWs.handle('liveMatchesUpdate', resp => {
        //console.log('liveMatchesUpdate:', resp)    
        let list = bookLiveModel.getList()

        let removeMap = {}
        if (resp.removedMatchIDs) {
            resp.removedMatchIDs.forEach(matchID => {
                removeMap[matchID] = true
            })
        }

        let newList = []
        
        list.forEach(old => {
            if (removeMap[old.matchID] === true) {
                return
            } else {
                newList.push(old)
            }
        })

        if (Array.isArray(resp.addedMatches)) {
            resp.addedMatches.forEach(newMatch => {
                newList.push(newMatch)
            })
        }

        bookLiveModel.setList(newList)
    })

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

    // tipper
    let tipperWs = new WebsocketClient({
       // url: 'ws://localhost:5759/ws'
//        url: 'ws://167.99.157.181:5759/ws'
        url: tipperWsURL
    })

    tipperWs.handle('interestingFootballMatches', resp => {
        console.log('interesting matches:', resp)
        
        if (Array.isArray(resp.matches)) {
            interesting.setList(resp.matches)
        }        
    })

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

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

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

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

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

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(1, allChampsTotal)
    m.set(2, allChampsTotal)
    m.set(3, allChampsTotal)

    /*
    m.set(11, topChampsTotal)
    m.set(22, topChampsTotal)
    m.set(33, topChampsTotal)

    m.set(701, myTotal)
    m.set(702, myTotal)
    m.set(703, myTotal)
    */
    
    let total = 0
    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 updateChamp(champ) {
    if (!champ.Champ) {
        return
    }
    let lastSync = moment(champ.LastSync * 1000).format("MMM DD, HH:mm:ss")

    switch (champ.Champ.champID) {
        case "/england/premier-league":
            document.getElementById('engLastSync').textContent = lastSync
            eng.setList(champ.Reports)
            break

        case "/germany/bundesliga":
            document.getElementById('gerLastSync').textContent = lastSync
            ger.setList(champ.Reports)
            break

        case "/italy/serie-a":
            document.getElementById('itaLastSync').textContent = lastSync
            ita.setList(champ.Reports)
            break

        case "/spain/laliga":
            document.getElementById('spaLastSync').textContent = lastSync
            spa.setList(champ.Reports)
            break
        
        case "/ukraine/premier-league":
            document.getElementById('ukrLastSync').textContent = lastSync
            ukr.setList(champ.Reports)
            break
        
        case "/portugal/primeira-liga":
            document.getElementById('porLastSync').textContent = lastSync
            por.setList(champ.Reports)
            break

        case "/switzerland/super-league":
            document.getElementById('swiLastSync').textContent = lastSync
            swi.setList(champ.Reports)
            break

        case "/turkey/super-lig":
            document.getElementById('turLastSync').textContent = lastSync
            tur.setList(champ.Reports)
            break

        case "/russia/premier-league":
            document.getElementById('rusLastSync').textContent = lastSync
            rus.setList(champ.Reports)
            break

        case "/belarus/vysshaya-liga":
            document.getElementById('belLastSync').textContent = lastSync
            bel.setList(champ.Reports)
            break

        case "/greece/super-league":
            document.getElementById('greLastSync').textContent = lastSync
            gre.setList(champ.Reports)
            break

        case "/montenegro/prva-crnogorska-liga":
            document.getElementById('monLastSync').textContent = lastSync
            mon.setList(champ.Reports)
            break
        
        case "/romania/liga-1":
            document.getElementById('romLastSync').textContent = lastSync
            rom.setList(champ.Reports)
            break

        case "/croatia/1-hnl":
            document.getElementById('croLastSync').textContent = lastSync
            cro.setList(champ.Reports)
            break

        case "/czech-republic/1-liga":
            document.getElementById('cheLastSync').textContent = lastSync
            che.setList(champ.Reports)
            break

        case "/denmark/superliga":
            document.getElementById('denLastSync').textContent = lastSync
            den.setList(champ.Reports)
            break
        
        case "/england/championship":
            document.getElementById('eng2LastSync').textContent = lastSync
            eng2.setList(champ.Reports)
            break
            
        case "/italy/serie-b":
            document.getElementById('ita2LastSync').textContent = lastSync
            ita2.setList(champ.Reports)
            break  
                        
        case "/spain/laliga2":
            document.getElementById('spa2LastSync').textContent = lastSync
            spa2.setList(champ.Reports)
            break  
    }
}



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


function modifyInterestingMatch(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.notes, 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)
}







