"""REST client handling, including finnhubStream base class."""

''' the examples online didnt have client.py. the methods found
in this client.py file are in the streams.py file of the examples. '''

import requests
from pathlib import Path
from typing import Any, Dict, Optional, Union, List, Iterable

from singer_sdk.helpers.jsonpath import extract_jsonpath
from singer_sdk.streams import RESTStream
from tap_finnhub_ohlc.auth import finnhubAuthenticator


SCHEMAS_DIR = Path(__file__).parent / Path("./schemas")


seconds_per_candle = {
    '1': 60,
    '5': 300,
    '15': 900,
    '30': 1800,
    '60': 3600,
    'D': 86400,
}


class finnhubStream(RESTStream):
    """finnhub stream class."""

    schema = PropertiesList(
        StringType('name', required=True),
        DateTimeType('timestamp'),
        FloatType('open'),
        FloatType('high'),
        FloatType('low'),
        FloatType('close'),
        FloatType('volume'),
    ).to_dict()

    primary_keys = ['name']

    @property
    def partitions(self) -> List[dict]:
        return self.config.get('assets', [])

    @property
    def url_base(self) -> str:
        """Return the API URL root, configurable via tap settings. 
        This is needed to specify the market desired, either FX or stocks."""

        return self.config.get('base_url')
        
    def get_url_params(self, partition: Optional[dict]) -> Dict[str, Any]:
        
        api_token = self.config.get('api_token')
        market = partition['symbol']
        symbol = partition['symbol']
        timeframe = partition['timeframe']
        num_candles = partition.get('num_candles', 900)

        # Convert num_candles to a timestamp
        end = round(time.time())
        start = end - (num_candles * seconds_per_candle[timeframe])


        r = requests.get(f'https://finnhub.io/api/v1/{market}/candle?symbol={symbol}&resolution={timeframe}&from={start}&to={end}&token={api_token}')


        return {
            'market': market,
            'symbol': symbol,
            'timeframe': timeframe,
            'start': start,
            'end': end,
            'api_token': api_token,
        }
    
    def get_recods(self, partition: dict, url_params: dict) -> Iterable[dict]:
        instrument = 

    # records_jsonpath = "$[*]"  # Or override `parse_response`.
    # next_page_token_jsonpath = "$.next_page"  # Or override `get_next_page_token`.


    def parse_response(self, response: requests.Response) -> Iterable[dict]:
        """Parse the response and return an iterator of result rows."""
        # TODO: Parse response body and return a set of records.
        yield from extract_jsonpath(self.records_jsonpath, input=response.json())

    # def post_process(self, row: dict, context: Optional[dict]) -> dict:
    #     """As needed, append or transform raw data to match expected structure."""
    #     # TODO: Delete this method if not needed.
    #     return row
