from time import sleep
from HorseRace.common import *
from HorseRace.horse import Horse
from datetime import date
from pathlib import Path

class Race(object):
    """docstring for ."""

    def __init__(self, id):
        self.id = id
        # self.name = name
        if len(self.id) == 12:
            self.set_race_info(self.id)

    def set_race_info(self,id):
        url = r"https://race.netkeiba.com/race/shutuba.html?race_id="+id
        sp = get_pages(url)
        race_name = ""
        race_name_pre =sp.find("div", class_="RaceName")
        if race_name_pre is None:
            print('データなし',id)
            return 0
        else:
            race_name = race_name_pre.text.replace('\n','')
        race_time=""
        race_dest=""
        race_time_pre = sp.find("div", class_="RaceData01").text
        if '/' in race_time_pre:
            race_time,race_dest = race_time_pre.replace('\n','').split(' / ')
        else:
            race_dest = race_time_pre.lstrip()
        race_site =sp.find("div", class_="RaceData02").text.replace('\n','')[2:4]
        d=sp.find("dl", id="RaceList_DateList")
        race_date=d.find("dd",class_="Active").text
        race_no=sp.find("span", class_="RaceNum").text
        self.horsePre = sp.find_all("span",class_="HorseName")
        self.name=race_name
        self.start_time=race_time
        s=race_dest
        self.dtype = s[0:1]
        self.distance = s[1:5]
        self.turn = s[s.find('(')+1:s.find(')')]
        self.weather = s[s.find('天候:')+3:s.find('天候')+4]
        self.cond = s[s.find('馬場:')+3:s.find('馬場:')+4]
        self.site=race_site
        self.no=race_no
        self.date=race_date
    def get_horse_info_in_race(self):
        horseInfo = []
        for hi in self.horsePre:
            if hi.text == '馬名':
                pass
            else:
                house_name = hi.text
                pos = str(hi).find('href=') + 6
                horse_no = str(hi)[pos+30:pos+30+10]
                horseInfo.append(Horse(horse_no,house_name))
        self.horse_info=horseInfo

class AllRaces(object):
    """docstring for .
    classにする必要ないかな"""

    def __init__(self):
        print('----driverを取得します----')
        self.driver = get_driver()
        sleep(3)
        print('----netkeibaにloginします----')
        self.driver = set_login(self.driver)
        sleep(3)
        print('----レース画面を表示します----')
        self.driver.get(r"https://race.netkeiba.com/top/?rf=navi")
        _ = input('対象日付に移動したら入力してください')
        sp = get_pages(self.driver.current_url)
        sleep(5)
        rs = self.driver.find_elements_by_class_name('RaceList_DataList')
        rsnames = [rsn.find_element_by_class_name('RaceList_DataTitle').text for rsn in rs ]
        print(rsnames)
        racelist = []
        for rss in rs:
            rsname = rss.find_element_by_class_name('RaceList_DataTitle').text
            rsis = rss.find_elements_by_class_name('RaceList_DataItem')
            for rsi in rsis:
                rsia = rsi.find_element_by_tag_name('a')
                rsin = rsi.find_element_by_class_name('Race_Num')
                rsi2 = rsi.find_element_by_class_name('RaceList_ItemContent')
                rsi2t = rsi2.find_element_by_class_name('ItemTitle')
                rsi2d = rsi2.find_element_by_class_name('RaceData')
                rsi2d2 = rsi2d.find_element_by_class_name('RaceList_Itemtime')
                rsi2d3 = rsi2d.find_elements_by_class_name('RaceList_ItemLong')
                if rsi2d3 is not None and rsi2d3 != []:
                    rsi2d3 = rsi2d3[0].text
                else:
                    rsi2d3 = '障害'
                rurl = rsia.get_attribute('href')
                rid = select_rid(rurl)
                ho = Race(rid)
                racelist.append((rsname,rsin.text,rsi2t.text,rsi2d2.text,rsi2d3,rurl,rid,ho))
        self.racelistpd = pd.DataFrame(racelist,columns=['会場','レースno','タイトル','発走時間','距離タイプ','URL','RID','ROBJ'])
        print(self.racelistpd[['会場','レースno','タイトル','発走時間','距離タイプ']])
        print('------一旦保存-------')
        rpath = Path(r"D:\horserace\data\race")
        if not rpath.exists():
            rpath = Path(r"E:\horserace\data\race")
        today = date.today()
        today = str(today.year) + str(today.month).zfill(2) + str(today.day).zfill(2)
        self.racelistpd.to_csv(rpath / (today + '.csv') )
    def get_s_driver(self):
        return self.driver
