#!/usr/bin/python3

import logging
import configparser
import lib.config
import lib.app_control
import lib.bluetooth

# we need to initially load the configuration file.
# This is loaded via a local symlink
myCar_config = configparser.ConfigParser()
myCar_config.read('data/etc/myCar.conf')

# fill in config values with defaults
myCar_config = lib.config.myCar_read_config_defaults(myCar_config)

# please note, that this VERSION string is filled by subversion
VERSION = '$Id$'

import atexit
atexit.register(lib.app_control.myCar_exit, myCar_config)


# lets start with log handling here
import logging, os
from pathlib import Path
# first check, if the logentry is a directory
if Path(myCar_config['paths'].get('log')).is_dir():
    # now check if we can write ther:
    myCar_logfile=myCar_config['paths'].get('log') + '/' + 'myCar_Application.log'
    try:    
        fp = open(myCar_logfile , 'w')
    except PermissionError:
        logging.warning('directory ' + myCar_logfile + ' not writeable')
    else:
        fp.close()
        logging.basicConfig(filename=myCar_logfile,level=logging.INFO)

        

from flask import Flask
from flask import url_for
from flask import render_template
from flask import request
from flask import redirect
from flask import abort
app = Flask(__name__)


@app.route('/')
def myCar_root():
    return render_template('index.html', VERSION=VERSION, bt_ctrl_ispowered=lib.bluetooth.bt_ctrl_ispowered())

@app.route('/bluetooth/controller')
def myCar_bluetooth_controller():
    return render_template('bluetooth/controller.html', VERSION=VERSION, bt_ctrl=lib.bluetooth.bt_getControllers())

@app.route('/bluetooth/devices')
def myCar_bluetooth_devices():
    if lib.bluetooth.bt_ctrl_ispowered == False:
        return render_template('bluetooth/controller.html', VERSION=VERSION, bt_ctrl=lib.bluetooth.bt_getControllers(), bt_error="All Bluetooth Adapters are powered off")
    else:
        return render_template('bluetooth/devices.html', VERSION=VERSION, bt_dev=lib.bluetooth.bt_getDevices())

@app.route('/bluetooth/connect', methods=['POST'])
def myCar_bluetooth_connect():
    # this method will connect to a bt device in the following order:
    #   - pair
    #   - trust
    #   - connect
    #try:
    #    request
    #except NameError:
    #    request = None

    try:
        if request is not None:
            
            import bluew

            #try:
            bt_dst_mac = request.form['bt_dst_mac']

            logging.info('Bluetooth trying to connect to ' + bt_dst_mac)
            # pair
            bluew.pair(bt_dst_mac)

            # trust
            bluew.trust(bt_dst_mac)

            # connect
            bluew.connect(bt_dst_mac)

            retstr = 'connected to '.join(bt_dst_mac)

        else:
            ret = 'Mac Address not provided'
    except NameError:
        ret = render_template('bluetooth/devices.html', VERSION=VERSION, bt_dev=bluew.devices(),bt_error="No MAC provided to connect to")
    except bluew.errors.DeviceNotAvailable:
        ret = render_template('bluetooth/devices.html', VERSION=VERSION, bt_dev=bluew.devices(),bt_error='Bluetooth device ' + bt_dst_mac +' is not available')

    return ret

@app.route('/conf')
def myCar_conf():
    # this method reads the configuration file
    # !!! beware due to stupidity in my mind this method also holds the 
    # !!! default vaules when the config file is not present
    return render_template('conf/main.html', VERSION=VERSION, config=myCar_config, sections=myCar_config.sections())
    
    
@app.route('/confsave', methods=['POST'])
def myCar_conf_save():
    # this method saves the configuration settings when posted, then redirects to context /conf
    if request is not None and request.form['configsend'] == 'save':

        myCar_config['paths'] = { 'app' : request.form['[paths][app]'],
                                  'log' : request.form['[paths][log]'],
                               'record' : request.form['[paths][record]'],
                               'export' : request.form['[paths][export]'] }
        # create the paths
        lib.config.myCar_save_pathcreate(myCar_config['paths'].get('app'),myCar_config['paths'].get('log'))
        lib.config.myCar_save_pathcreate(myCar_config['paths'].get('app'),myCar_config['paths'].get('record'))
        lib.config.myCar_save_pathcreate(myCar_config['paths'].get('app'),myCar_config['paths'].get('export'))

        myCar_config['connections'] = { 'bt_dev' : request.form['[connections][bt_dev]'],
                                        'gps_dev' : request.form['[connections][gps_dev]'],
                                        'wifi_pwd' : request.form['[connections][wifi_pwd]'] }

        myCar_config['startup'] = { 'bt_connect' : request.form['[startup][bt_connect]'],
                                    'autorecord' : request.form['[startup][autorecord]'] }

        myCar_config['metrics'] = { 'temperature' : request.form['[metrics][temperature]'],
                                    'speed' : request.form['[metrics][speed]'] }

        lib.config.myCar_save_config(myCar_config)

    return redirect(url_for('myCar_conf'), code=302)
            

@app.route('/gps')
def myCar_gps():
    # dummy implementation before code is ready
    return render_template('empty.html', VERSION=VERSION)
    
@app.route('/wifi')
def myCar_wifi():
    # dummy implementation before code is ready
    return render_template('empty.html', VERSION=VERSION)

@app.route('/system')
def myCar_system():
    # dummy implementation before code is ready
    return render_template('empty.html', VERSION=VERSION)


@app.route('/live')
def myCar_live():
    # dummy implementation before code is ready
    return render_template('empty.html', VERSION=VERSION)


@app.route('/record')
def myCar_record():
    # dummy implementation before code is ready
    # - first readout the available files
    # - then readout the trips from the files
    import lib.recordings
    flist = []
    fpflist = lib.recordings.myCar_rec_files(myCar_config['paths'].get('app') + '/' + myCar_config['paths'].get('record'))
    for f in fpflist:
        flist.add(str(f).strip(myCar_config['paths'].get('app') + '/' + myCar_config['paths'].get('record')))

    return render_template('recordings/overview.html', VERSION=VERSION, files=flist, fpfiles=fpflist)

# error handling
@app.errorhandler(404)
def page_not_found(error):
    return render_template('404/error.html'), 404

