# -*- coding: utf-8 -*-
'''
***************************************************************************
    bahn_query.py
    ---------------------
    Date                 : October 2019
    Copyright            : (C) 2019 by Christoph Franke
    Email                : franke at ggr-planung dot de
***************************************************************************
*                                                                         *
*   This program is free software: you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 3 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************

scrapers for public stops and public transport connections
'''

__author__ = 'Christoph Franke'
__date__ = '29/10/2019'
__copyright__ = 'Copyright 2019, HafenCity University Hamburg'

import datetime
from datetime import datetime, date, timedelta

from projektcheck.utils.connection import Request

requests = Request(synchronous=True)

class BahnQuery(object):
    '''
    Deutsche-Bahn-scraper for connections, stops and time tables
    '''
    timetable_url = 'https://reiseauskunft.bahn.de/bin/bhftafel.exe/dn'

    # default request parameters for timetables
    timetable_params = {
        'ld': 96242,
        'country': 'DEU',
        'rt': 1,
        'bt': 'dep',
        'start': 'yes',
        'productsFilter': 1111111111,
        'max': 10000,
        'maxJourneys': 10000,
        'time': '7:00',
        'date': ''
    }

    date_pattern = '%d.%m.%Y'

    def __init__(self, date=None, timeout=0):
        '''
        Parameters
        ----------
        date : datetime.date, optional
            date to scrape data for, defaults to today
        timeout : int, optional
            pause between requests in seconds to avoid block due to too many
            requests, defaults to no pause
        '''
        date = date or datetime.date.today()
        self.date = date.strftime(self.date_pattern)
        self.timeout = timeout

    def get_timetable_url(self, stop_name):
        '''
        set up an url to request the stop with given id
        '''
        params = self.timetable_params.copy()
        params['date'] = self.date
        params['input'] = stop_name
        args = ['{}={}'.format(v, k) for v, k in params.items()]
        url = f'{self.timetable_url}?{"&".join(args)}'
        return url

def next_monday():
    '''
    Returns
    -------
    datetime.date
       the next monday proceeding from today
    '''
    today = date.today()
    nextmonday = today + timedelta(days=-today.weekday(), weeks=1)
    return nextmonday
