from flask import Blueprint, render_template, redirect, url_for, request
from functools import wraps
import subprocess

from luniebox import luniebox

pages = Blueprint('pages', __name__)


def setup_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not luniebox.get_setting('luniebox', 'setup'):
            return redirect(url_for('pages.setup'))
        return f(*args, **kwargs)
    return decorated_function


@pages.route("/setup")
def setup():
    model = {}

    if luniebox.get_setting('luniebox', 'setup'):
        model['setup'] = True

    model['client-id'] = luniebox.get_setting('spotify', 'client_id')
    model['client-secret'] = luniebox.get_setting('spotify', 'client_secret')
    model['redirect-uri'] = luniebox.get_setting('spotify', 'redirect_uri')

    model['username'] = luniebox.spotify.get_setting('username', '')
    model['password'] = luniebox.spotify.get_setting('password', '')
    model['device-name'] = luniebox.spotify.get_setting('device_name', '')

    model['host'] = request.host_url

    if model['host'].endswith("/"):
        model['host'] = model['host'][:len(model['host']) - 1]

    if not model['redirect-uri']:
        model['redirect-uri'] = model['host'] + url_for('api.spotify_callback')

    return render_template('setup.html', model=model)


@pages.route("/")
@setup_required
def index():
    devices = luniebox.spotify.devices()
    device_id = luniebox.get_setting('spotify', 'device_id')
    device_name = luniebox.spotify.get_setting('device_name')

    mpdStatus = luniebox.mpd_status()

    spotifyStatus = {
        'status': False,
        'device_name': device_name,
        'device_id': device_id,
        'errors': {'setup': True, 'not_running': True}
    }

    if not device_id:
        spotifyStatus['errors']['not_running'] = False
        for device in devices['devices']:
            if device['name'] == device_name:
                device_id = device['id']
                luniebox.set_setting('spotify', 'device_id', device_id)
                spotifyStatus['errors']['setup'] = False
    else:
        spotifyStatus['errors']['setup'] = False
        for device in devices['devices']:
            if device['id'] == device_id:
                spotifyStatus['errors']['not_running'] = False

    if spotifyStatus['errors']['not_running'] and luniebox.spotify.transfer_playback():
        spotifyStatus['errors']['not_running'] = False

    if not spotifyStatus['errors']['setup'] and not spotifyStatus['errors']['not_running']:
        spotifyStatus['status'] = luniebox.spotify.playback_state()

    daemon_error = False
    daemon_status = subprocess.call(
        ["systemctl", "is-active", "--quiet", "luniebox-daemon"])

    if daemon_status == 0:
        daemon_status = "Running"
    else:
        daemon_error = "Not running"
        daemon_status = False

    return render_template('index.html', spotify=spotifyStatus, mpd=mpdStatus, daemon_status=daemon_status, daemon_error=daemon_error)


@pages.route("/success")
@setup_required
def success():
    success = {}
    if 'play' in request.args:
        success['play'] = request.args['play']

    if 'spotify_dl' in request.args:
        success['spotify_dl'] = request.args['spotify_dl']

    if 'restart_spotifyd' in request.args:
        success['restart_spotifyd'] = request.args['restart_spotifyd']

    if 'restart_mpd' in request.args:
        success['restart_mpd'] = request.args['restart_mpd']

    if 'start_daemon' in request.args:
        success['start_daemon'] = request.args['start_daemon']

    if 'stop_daemon' in request.args:
        success['stop_daemon'] = request.args['stop_daemon']

    if 'rfid_play' in request.args:
        success['rfid_play'] = request.args['rfid_play']

    if 'rfid_read' in request.args:
        success['rfid_read'] = request.args['rfid_read']

    if 'rfid_write' in request.args:
        success['rfid_write'] = request.args['rfid_write']

    return render_template('success.html', success=success)


@pages.route("/error")
@setup_required
def error():
    error = False
    if 'error' in request.args:
        error = request.args['error']

    return render_template('error.html', error=error)


@pages.route("/spotify/search", methods=['GET', 'POST'])
def spotify_search():
    query = '' if not 'q' in request.args else request.args['q']
    types = [
        'track', 'album'] if not 'type' in request.args else request.args.getlist('type')
    offset = 0 if not 'offset' in request.args else request.args['offset']

    limit = 5
    if not 'limit' in request.args:
        if len(types) == 1:
            limit = 20
        if len(types) == 2:
            limit = 10
    else:
        limit = int(request.args['limit'])

    results = False if not query else luniebox.spotify.search(
        query, types, limit, offset)

    if results:
        for result in results.values():
            if 'items' in result:
                for item in result['items']:
                    if luniebox.spotifydl_connect():
                        item['spotifydl'] = str(
                            luniebox.spotifydl.downloadStatus(item['uri']))

    return render_template('spotify_search.html', results=results, query=query, types=types, limit=limit, offset=offset)


@pages.route("/spotify/download", methods=['GET'])
def spotifydl():
    status = False
    if 'status' in request.args:
        status = request.args['status']
    uri = False
    if 'uri' in request.args:
        uri = request.args['uri']
    return render_template('spotifydl.html', status=status, uri=uri)


@pages.route("/mpd/list", methods=['GET'])
def mpd_list():
    path = ''
    spotify = False
    if 'path' in request.args:
        path = request.args['path']

    if 'spotify' in request.args:
        spotify = True

    results = luniebox.mpd_list(path)
    return render_template('mpd.html', results=results, path=path, spotify=spotify)
