# -*- coding: utf-8 -*-
"""SIP Master Controller (REST)."""
import os

import redis
from flask import request
from flask_api import FlaskAPI, status


APP = FlaskAPI(__name__)
DB = redis.Redis(host=os.getenv('DATABASE_HOST'))


@APP.route('/')
def root():
    """."""
    return {
        "message": "Welcome to the SIP Master Controller",
        "_links": {
            "items": [
                {"href": "{}state".format(request.url)}
            ]
        }
    }


@APP.route('/state', methods=['GET', 'PUT'])
def state():

    """Return the SDP State."""
    states = ['OFF', 'STANDBY', 'ON', 'DISABLE']

    if request.method == 'PUT':
        requested_state = request.data.get('state', '').upper()
        if requested_state not in states:
            return ({'error': 'Invalid state: {}'.format(requested_state),
                     'allowed_states': states},
                    status.HTTP_400_BAD_REQUEST)
        response = {'message': 'Accepted state: {}'.format(requested_state)}
        try:
            DB.set('state', requested_state)
        except redis.exceptions.ConnectionError:
            response['error'] = 'Unable to connect to database.'
        return response

    try:
        current_state = DB.get('state')
        if current_state is None:
            DB.set('state', 'INIT')
            current_state = 'INIT'
        else:
            current_state = current_state.decode('utf-8')
        return {'state': '{}'.format(current_state)}
    except redis.exceptions.ConnectionError:
        return {'state': 'UNKNOWN',
                'error': 'Unable to connect to database.'}


@@ -62,16 +62,30 @@
 mport os
+%0Aimport signal
 %0A%0Aimport
@@ -564,24 +564,73 @@
 DP State.%22%22%22
+%0A%0A    # These are the states we allowed to rquest
 %0A    states 
@@ -1239,24 +1239,195 @@
     
-return response%0A
+if requested_state == 'OFF':%0A            os.kill(os.getpid(), signal.SIGINT)%0A        return response%0A%0A    # GET - if the state in the database is OFF we want to replace it with%0A    # INIT
 %0A   
@@ -1504,16 +1504,58 @@
  is None
+ or current_state.decode('utf-8') == 'OFF'
 :%0A      
@@ -1884,9 +1884,8 @@
 base.'%7D%0A
-%0A

Implement shutdown when OFF is PUT