"""
Connect with the HTTP API of a BlackVue dashcam. Use the tool to sync files
or modify settings.

Usage:
  blackvue_wifi --download-all-recordings <foldername>
  blackvue_wifi --download-missing-recordings [--continuously] <foldername>
"""
import warnings

import confidence
import requests
import wget
from docopt import docopt
from tqdm import tqdm


class BlackVueClient:

    def __init__(self, config=None):
        """
        An HTTP API client for BlackVue dashcams.
        :param config: an object containing configuration (generated by
        docopt or confidence for example)
        """
        self.endpoint = config.endpoint
        if not self.dashcam_present():
            warnings.warn('Could not find a connected dashcam')

    def dashcam_present(self):
        """
        Boolean indicating presence of a dashcam.

        :return: True if dashcam is found, False otherwise
        """
        try:
            return 'BlackVue' in self.get('', timeout=5).text
        except requests.exceptions.ConnectTimeout:
            return False
        except requests.ConnectionError:
            return False

    def list_recordings(self):
        """
        List all recordings on the connected dashcam.

        :return: a list of recordings
        """
        lines = self.get('blackvue_vod.cgi').text.split('\n')
        version, recordings = lines[0], lines[1:]
        recordings = [recording.split(',') for recording in recordings]
        recordings = [recording[0].split(":")[1] for recording in
                      recordings[:-1]]
        return recordings

    def download_all_recordings(self, *args, **kwargs):
        """
        Download all recordings on the connected dashcam with wget for Python.
        """
        for recording in tqdm(self.list_recordings()):
            self.download(recording, *args, **kwargs)

    def get_config(self):
        """

        :return:
        """
        return self.get('Config/config.ini').text

    def set_config(self):
        """

        :return:
        """

    def get_dashcam_metadata(self):
        """

        :return:
        """
        return self.get('Config/version.bin').text

    def upload(self):
        """

        :return:
        """

    def absolute_url(self, path):
        """
        Create a full URL from a partial path.

        :param path: a relative URL
        :return: full URL
        """
        return "/".join(['http:/', self.endpoint, path])

    def post(self, path, *args, **kwargs):
        return requests.post(self.absolute_url(path),
                             *args, **kwargs)

    def get(self, path, *args, **kwargs):
        return requests.get(self.absolute_url(path),
                            *args, **kwargs)

    def download(self, path, *args, **kwargs):
        return wget.download(self.absolute_url(path),
                             *args, **kwargs)


def main():
    client = BlackVueClient(config=confidence.Configuration(
        confidence.Configuration({'endpoint': '10.99.77.1'}),
        confidence.load_name('blackvue'),
        confidence.Configuration(docopt(__doc__))
    ))
    options = docopt(__doc__)
    if options['--download-all-recordings']:
        client.download_all_recordings(out=options['<foldername>'])
    if options['--download-missing-recordings']:
        if options['--continuously']:
            print("Continous syncing will be included in the next version")
        else:
            print("Incremental downloads will be included in the next version")


if __name__ == "__main__":
    main()
