# from scrapUtil import get_pages, get_tables
from HorseRace.common import get_pages, get_tables
from HorseRace import common as c
from HorseRace import training as t
from time import sleep
import pandas as pd
import json
from pathlib import Path
from typing import Dict


class Horse():
    """docstring for ."""

    def __init__(self, id,name):
        self.id = id
        self.name = name
        self.profile = {}
        self.blood = {}
        self.past_race = {}
        self.saved_data = False # 過去の出走データを持っているか
        self.has_profile = False # 馬プロフィールデータを持っているか
        self.past_traindatas_boo = False # 過去の調教データを持っているか
        # D driverにあれば抽出　＆　比較
        hpath = Path(r"D:\horserace\data\horse")
        if not hpath.exists():
            hpath = Path(r"E:\horserace\data\horse")
        self.sp = hpath / (self.id+self.name)
        self.sp.mkdir(exist_ok=True)
        self.hdatap = self.sp / "hdata.json" # profile
        self.hdata = self.sp / 'past_race.csv' # past_race
        self.hdatat = self.sp / "past_train.csv" # past_train
        if hpath.exists() and self.hdatap.exists():
            with open(str(self.hdatap),'r',encoding='utf-8') as f:
                sd = json.load(f)
                self.blood = sd['blood']
                self.profile = sd['profile']
                self.has_profile = True
        if hpath.exists() and self.hdata.exists():
            self.past_race = pd.read_csv(self.hdata)
            self.saved_data = True
        elif len(self.id) == 10 and self.saved_data is False:
            print('self.set_horse_info(driver)を実行してください')
        if hpath.exists() and self.hdatat.exists():
            self.past_traindatas = pd.read_csv(self.hdatat)
            if len(self.past_traindatas) > 0:
                self.past_traindatas_boo = True
    def set_horse_info(self, indriver):
        url = r"https://db.netkeiba.com/horse/"
        indriver.get(url+self.id)
        sleep(2)
        data = get_tables(indriver.page_source)
        dd = data[1].to_dict()
        for d in dd[0]:
            self.profile[dd[0][d]] = dd[1][d]
        self.blood['f'] = data[2][0][0]
        self.blood['m'] = data[2][0][2]
        self.blood['ff'] = data[2][1][0]
        self.blood['fm'] = data[2][1][1]
        self.blood['mf'] = data[2][1][2]
        self.blood['mm'] = data[2][1][3]
        if len(data) > 4 and hasattr(data[3],'受賞歴'):
            data[3] = data[4]
        if len(data) < 4 or 'コース適性' in str(data[3]):
            print('過去レース情報なし',self.id)
        else:
            dd = data[3].rename(columns={'勝ち馬(2着馬)':'勝馬'})
            header = ['日付','開催','天気','レース名','距離','馬場', '馬場指数',
                '頭数','枠番','馬番','人気','着順','着差','騎手','ﾀｲﾑ指数',
                '斤量','タイム','通過','ペース','上り','馬体重','勝馬']
            dd["着順"] = pd.to_numeric(dd["着順"], errors='coerce')
            dd["人気"] = pd.to_numeric(dd["人気"], errors='coerce')
            self.past_race = dd[header]
        self.save_horse_data()
    def save_past_race_data(self):
        try:
            self.past_race.to_csv(self.hdata)
            self.saved_data = True
        except:
            print('dataがありません',self.name)

    def cln_past_data(self):
        try:
            self.past_race['開催'] = self.past_race['開催'].replace('[0-9]','',regex=True)
            self.past_race['グレード'] = self.past_race['レース名'].apply(c.categorize_races_bk)
            self.past_race['タイム2'] = self.past_race['タイム'].apply(c.convert_time2)
            # self.past_race['上り2'] = self.past_race['上り'].apply(c.convert_time3)
            print(len(self.past_race),'len()')
            if len(self.past_race) == 1:
                self.past_race['タイプ'] = self.past_race['距離'].str[0]
                self.past_race['距離'] = self.past_race['距離'].str[1:]
            else:
                self.past_race = self.past_race.apply(c.split_distance,axis=1)
            self.result_ana_boo = True
        except Exception as e:
            print(e)
            self.result_ana = ''
            self.result_ana_boo = False
            print(self.past_race)
    def get_traindatas(self, indriver):
        url = r"https://db.netkeiba.com/?pid=horse_training&id="+self.id
        try:
            self.past_traindatas = t.select_traindatas(url,indriver)
            self.past_traindatas_boo = True
        except:
            print('err')
    def save_horse_data(self):
        sd = {}
        sd['id'] = self.id
        sd['name'] = self.name
        sd['blood'] = self.blood
        sd['profile'] = self.profile
        with open(str(self.hdatap),'w',encoding='utf8') as f:
            json.dump(sd, f, indent=4, ensure_ascii=False)
            self.has_profile = True
        if self.past_traindatas_boo :
            self.past_traindatas.to_csv(self.hdatat)
        self.save_past_race_data()
    def cln_train_data(self):
        if self.past_traindatas_boo:
            self.past_traindatas = self.past_traindatas.apply(lambda x:t.cln_train_time2(x), axis=1)
            self.past_traindatas['レース'] = self.past_traindatas['対象レース時'].apply(lambda x:c.select_racename(x))
            self.past_traindatas['グレード'] = self.past_traindatas['レース'].apply(c.categorize_races)
            self.past_traindatas['対象レース時日付'] = self.past_traindatas['対象レース時'].str[:10]
            p = r'D:\horserace\data\ana'
            if not p.exists():
                p = r'E:\horserace\data\ana'
            p = p / "train_mean.csv"
            cdf = pd.read_csv(p)
            self.past_traindatas.調教タイム1 = self.past_traindatas.調教タイム1.astype(float)
            self.past_traindatas.調教タイム2 = self.past_traindatas.調教タイム2.astype(float)
            self.past_traindatas.調教タイム3 = self.past_traindatas.調教タイム3.astype(float)
            self.past_traindatas.調教タイム4 = self.past_traindatas.調教タイム4.astype(float)
            self.past_traindatas.調教タイム5 = self.past_traindatas.調教タイム5.astype(float)
            self.past_traindatas = self.past_traindatas.apply(lambda x :t.compare_standard_time(x,cdf) , axis=1)
    def get_data_for_machine_learning(self):
        if self.past_traindatas_boo and self.result_ana_boo:
            databk = pd.merge(self.past_traindatas, self.past_race, left_on='対象レース時日付', right_on='日付', how='left')
            databk.日付_x = databk.日付_x.str[0:10]
            databk.馬場.unique()
            map_baba = {'良':1, '重':3, '稍':2}
            databk.馬場 = databk.馬場.map(map_baba)
            databk.脚色.unique()
            map_asi = {'仕掛':2.5, '馬也':1, '一杯':3, '強め':2, 'Ｇ強':2}
            databk.脚色 = databk.脚色.map(map_asi)
            databk.評価.unique()
            map_hyo = {'平行線':3, '順調':4, '目立たず':3, '出来安定':3.5, '変わらず':3, '気配平凡':3, '動き平凡':3, '調整程度':3,
            '多少良化':3.5, '動き軽快':4, 'やや良化':3.5, '意欲十分':4, '仕上がる':4, '出来は良':3.5, '反応上々':4, '状態良好':4,
            '仕上るも':3.5, 'まずまず':3.5, '仕上十分':4, '伸び上々':4, '動き上々':4, '元気一杯':4, '攻め熱心':4, '好気合':4,
            '好調持続':4, '気配上々':4, '仕上良好':4, 'キビキビ':4, '好調子':4, '仕上上々':4, '素軽い':4, '好気配':4,
            '変身十分':4}
            databk.評価 = databk.評価.map(map_hyo)
            # '映像' 実は評価
            map_hyo2 = {'E':1,'D':2,'C':3,'B':4,'A':5}
            databk['評価点'] = databk.映像.map(map_hyo2)
            didx = databk[databk['グレード_y'].isnull()].index
            databk = databk.drop(didx)
            databk.グレード_y = databk.グレード_y.str[0:2].astype(int)*-1+16
            # '対象レース時日付'　本日からどれくらい離れてるかで数値に使用
            from datetime import datetime
            td = datetime.today()
            databk.日付_x = pd.to_datetime(databk.日付_x)
            databk['調教日付'] = (td - databk['日付_x']).astype('timedelta64[D]')
            databk.対象レース時日付 = pd.to_datetime(databk.対象レース時日付)
            databk['対象レース時日付'] = (td - databk['対象レース時日付']).astype('timedelta64[D]')
            map_tenki = {'晴':4, '曇':3, '小雨':2.5, '雨':2, '雪':1}
            databk['天気'] = databk.天気.map(map_tenki)
            header = ['対象レース時日付', 'グレード_y','結果','開催','タイプ','距離','天気','タイム2','上り'
             , '調教日付', '評価点', 'コース',# '馬場' ,  '乗り役', '位置',
             '脚色', '調教タイム1', '調教タイム2', '調教タイム3', '調教タイム4', '調教タイム5',
             '調教タイム合計', '調教基準比較上り', '調教基準比較', '調教基準比較平均' ]
            data = databk[header]
            data['距離'] = pd.to_numeric(data['距離'], errors='coerce')
            # nanを除く
            data = data.dropna(subset=['調教タイム合計'])
            data = data.dropna(subset=['脚色'])
            data = data.dropna(subset=['結果'])
            return data
        else:
            print('nothing')




if __name__ == '__main__':
    pass
txt='''

'past_race.csv'をBKにする
from pathlib import Path
p = Path(r"D:\horserace\data\horse")
horses = p.glob('*')
for horse in horses:
    pr = horse / 'past_race.csv'
    if pr.exists():
        pr.rename(pr.parent / ('bk20220211_'+pr.name))
    else:
        print('dataなし',str(pr))


from HorseRace.horse import Horse
from HorseRace.common import *
driver = get_driver()
set_login(driver)
horse = Horse('2016106606','カラテ')
if not horse.saved_data:
    horse.set_horse_info(driver)

horse.past_race
'''
