from flask import Flask, render_template, request, redirect, url_for, session
import csv
import os
import pandas as pd
import tkinter as tk
from tkinter import messagebox
from pyvis.network import Network


app = Flask(__name__)
app.secret_key = 'your_secret_key'  # セッションの安全性のためのキーを設定

@app.route('/')
def home():
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    import time
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.chrome.service import Service as ChromeService
    from webdriver_manager.chrome import ChromeDriverManager
    from pathlib import Path
    import pandas as pd
    import os
    start_year = 2000
    options = webdriver.ChromeOptions()
    #options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    dldir_path = Path('csv')  # csv という名前のフォルダとする
    dldir_path.mkdir(exist_ok=True)  # なければ作成
    download_dir = str(dldir_path.resolve())  # 絶対パスを取得
    print("download_dir: " + download_dir)

    options.add_experimental_option('prefs', {    # Chrome のオプションに
    'download.default_directory': download_dir  # 絶対パスで指定  
    })
    service = Service(executable_path='C:/Users/Owner/OneDrive - 富山県立大学/研究室/卒業研究/chromedriver-win64/chromedriver-win64/chromedriver.exe')
    driver = webdriver.Chrome(service=service, options=options)
    driver.implicitly_wait(10)
    # for i in range(1,3): 
    #  print(i)
    #  driver.get("https://www.stat-search.boj.or.jp/")
    #  elem = driver.find_element(By.XPATH, '//*[@id="toukei_4"]/a')
    #  elem.click()
    #  elem = driver.find_element(By.XPATH, '//*[@id="toukei_4"]/ul/li['+str(i)+']/a')
    #  elem.click()
    #  elem_tenkai = driver.find_element(By.XPATH, '//*[@id="menuSearchTabpanel"]/div[2]/div[1]/div[2]/input')
    #  elem_tenkai.click()
    #  elem_check = driver.find_element(By.XPATH, '//*[@id="menuSearchDataCodeList"]/tbody/tr[1]/td/label')
    #  elem_check.click()
    #  elem = driver.find_element(By.XPATH, '//*[@id="menuSearchTabpanel"]/div[2]/div[2]/div[4]/a')
    #  elem.click()
    #  elem_start_year = driver.find_element(By.XPATH, '//*[@id="fromYear"]')
    #  start_year = elem_start_year.send_keys(start_year)
    #  elem = driver.find_element(By.XPATH, '//*[@id="resultArea"]/div[4]/ul/li[1]/a')
    #  elem.click()
    #  handle_array = driver.window_handles
    #  driver.switch_to.window(handle_array[i])
    #  elem = driver.find_element(By.XPATH, '/html/body/div[2]/div/div[2]/table/tbody/tr[2]/td[5]/a')
    #  elem.click()
    #  handle_array = driver.window_handles
    #  driver.switch_to.window(handle_array[i+1])
    #  elem = driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div/table/tbody/tr/td/a')
    #  elem.click()
    url=driver.get("https://indexes.nikkei.co.jp/nkave/index/profile?idx=nk500av")
    click_elem = driver.find_element(By.XPATH, '/html/body/div[1]/div/main/section[3]/div/nav/ul/li[2]/a').get_attribute('href')
    driver.get(click_elem)
    time.sleep(3)
    os.remove('csv/nwe.csv')
    old_csv = "csv/nikkei_500_stock_average_daily_jp.csv"
    new_csv = "csv/nwe.csv"
    os.rename(old_csv,new_csv)
    # click_elem = driver.find_element(By.XPATH, '/html/body/div[1]/div/main/section[3]/div/nav/ul/li[2]/a').get_attribute('href')
    # click_elem
    # driver.get(click_elem)
    # for i in range(30):                       /html/body/div[1]/div/main/section[3]/div/nav/ul/li[2]/a
    #     click_elem.click()
    # elem = driver.find_element(By.XPATH, '//*[@id="fourvalue_timeline"]/tbody')
    # print(elem.text)
    file_path = "C:/Users/Owner/OneDrive - 富山県立大学/デスクトップ/flask/csv/nwe.csv"

    try:
        df = pd.read_csv(file_path, encoding='cp932')  # エンコーディングを適切なものに変更
        df["データ日付"] = pd.to_datetime(df["データ日付"], errors='coerce', format='%Y/%m/%d')
    except UnicodeDecodeError as e:
        print(f"CSVファイルの読み込みエラー: {e}")
    except ValueError as ve:
        print(f"日付の変換エラー: {ve}")

    df["データ日付"] = pd.to_datetime(df["データ日付"], format='%Y/%m/%d')
    df = df.set_index('データ日付')

    #不必要なカラムを削除。今回の指数の値は全て終値で示します。
    df = df.drop(['始値', '高値', '安値'], axis=1)
    df = df.sort_index(ascending=True)

    #名前の変更
    df.rename(columns={'終値':'Nikkei500','業種別（水産）終値':'Fishery', '業種別（鉱業）終値':'Mining', '業種別（建設）終値':'Construction', '業種別（食品）終値':'Foods',\
    '業種別（繊維）終値':'Fiber','業種別（パルプ・紙）終値':'Pulp & paper', '業種別（化学）終値':'Chemicals', '業種別（医薬品）終値':'Pharmaceuticals',\
    '業種別（石油）終値':'Petroleum','業種別（ゴム）終値':'Rubber', '業種別（窯業）終値':'Glass & Ceramics','業種別（鉄鋼）終値':'Steel','業種別（非鉄・金属）終値':'Nonferrous metals',\
    '業種別（機械）終値':'Machinery','業種別（電気機器）終値':'Electric machinery','業種別（造船）終値':'Shipbuilding','業種別（自動車）終値':'Automotive',\
    '業種別（輸送用機器）終値':'Transportation instruments','業種別（精密機器）終値':'Precision instruments', '業種別（その他製造）終値':'Other manufacturing','業種別（商社）終値':'Trading companies',\
    '業種別（小売業）終値':'Retail','業種別（銀行）終値':'Banking','業種別（その他金融）終値':'Other financial services','業種別（証券）終値':'Securities',\
    '業種別（保険）終値':'Insurance','業種別（不動産）終値':'Real estate','業種別（鉄道・バス）終値':'Railway/bus','業種別（陸運）終値':'Land transport',\
    '業種別（海運）終値':'Marine transport', '業種別（空運）終値':'Air transport', '業種別（倉庫）終値':'Warehousing', '業種別（通信）終値':'Communications',\
    '業種別（電力）終値':'Electric power', '業種別（ガス）終値':'Gas', '業種別（サービス）終値':'Services'}, inplace=True)
    pd.set_option('display.max_rows', None)
    pd.set_option('display.max_columns', None)
    # dfの最後の行を削除
    df = df.drop(df.index[-1])
    print(df)
    df.to_csv('tests.csv',encoding="cp932")
    print(f"File saved to: {os.path.abspath('tests.csv')}")
    return render_template('flash.html')
    
if __name__ == '__main__':
    app.run(debug=True)