import datetime
import pandas as pd
import yfinance as yf
from pathlib import Path


class Stock:
    """
    Stock class is responsible for fetching and caching stock data
    """
    # contains fetched data in a dataframe
    df = None

    def __init__(self,
                 name,
                 start: datetime.datetime,
                 end: datetime.datetime,
                 force_fetch_stock=False):

        self.name = name
        self.start = start
        self.end = end
        self.force_fetch_stock = force_fetch_stock

    def fetch(self):
        # check if data is already cached or should be fetched anyway
        if not self._stored() or self.force_fetch_stock:
            try:
                # fetch and cache
                self.df = yf.download(self.name, start=self.start, end=self.end)
                self._cache()
            except Exception as ex:
                # if fetching fails, print exception and quit
                print(ex)
                quit()
        else:
            # load dataset from cache
            self._load()

    # check if data is already stored
    def _stored(self):
        return Path('stocks/' + self._filename()).is_file()

    # cache data
    def _cache(self):
        self.df.to_csv('stocks/' + self._filename())

    # load data
    def _load(self):
        self.df = pd.read_csv('stocks/' + self._filename(), index_col=0, parse_dates=True)

    # compute file name
    def _filename(self):
        return self.name + '-' + self.start.strftime("%d-%m-%Y") + '-' + self.end.strftime("%d-%m-%Y") + '.csv'
