#!/usr/bin/env python3
#
#  digital-audio-amp
#
# 

import sys
import time
from barix.amp.tas2770 import *
from barix.amp.tas6421 import *
from flask import Flask, request, jsonify

if __name__ == "__main__":
    
    HTTP_API_PORT = 50555

    if len(sys.argv) == 4:
        amp_name = str(sys.argv[1])
        i2c_addr = int(sys.argv[2],0) 
        amp_vol = int(sys.argv[3],0)
    elif len(sys.argv) == 7:
        amp_name = str(sys.argv[1])
        i2c_addr = int(sys.argv[2],0)
        amp_vol = int(sys.argv[3],0)
        power_source = str(sys.argv[4])
        impedance = str(sys.argv[5])
        json_file = str(sys.argv[6])
    else:
        print("USAGE:   python3 digital-audio-amp.py amp_name i2c_addr amp_vol")
        print("         or")
        print("         python3 digital-audio-amp.py amp_name i2c_addr amp_vol power_source impedance amp.json")
        print(" amp_name:       tas2770, tas6421")
        print(" i2c_addr:       amplifier i2c address")
        print(" amp_vol:        amplifier volume -- please check amplifier datasheet")
        print(" power_source:   external, poe, poe+, poe3, poe4")
        print(" impedance:      auto, 4, 8")
        print(" amp.json:       amplifier settings json file")
        sys.exit(1)
    
    if amp_name == "tas2770":
        amp = TAS2770(0,i2c_addr,amp_vol)
        amp.setupAmp()
    elif amp_name == "tas6421":
        amp = TAS6421(0,i2c_addr,amp_vol)
        amp.setupAmp()
        time.sleep(2)
        amp.impedanceMeasurement()
        amp.selectGainVol(power_source, impedance, json_file)
        amp.setupAmp()
    else:
        print("Invalid digital amplifier!")
        sys.exit(1)
    
    app = Flask(__name__)
    
    @app.route('/api/amp/init', methods=['POST'])
    def init():
        amp.setupAmp()
        return "init amplifier", 201
    
    @app.route('/api/amp/vol', methods=['POST','GET'])
    def vol():
        if request.method == 'POST':
            content = request.get_json(silent=False)
            amp.setVol(int(content['amp_vol'],0))
            return "set amplifier volume to {}".format(content['amp_vol']), 201
        if request.method == 'GET':
            return jsonify({"amp_vol": amp.getVol()})
    
    @app.route('/api/amp/gain', methods=['POST','GET'])
    def gain():
        if request.method == 'POST':
            content = request.get_json(silent=False)
            amp.setGain(int(content['amp_gain'],0))
            return "set amplifier gain to {}".format(content['amp_gain']), 201
        if request.method == 'GET':
            return jsonify({"amp_gain": amp.getGain()})

    @app.route('/api/amp/temp', methods=['GET'])
    def temperature():
        return jsonify({"temperature": amp.readTemp()})
        
    @app.route('/api/amp/speaker_imp', methods=['GET'])
    def get_impedance():
        return jsonify({"impedance": amp.getImpedance()})

    @app.route('/api/amp/over_temp', methods=['GET'])
    def get_over_temp():
        return jsonify({"over_temp": amp.getOverTemp()})

    @app.route('/api/amp/mode', methods=['GET'])
    def get_amp_mode():
        return jsonify({"mode": amp.checkAmpMode()})

    app.run(host='0.0.0.0', port=HTTP_API_PORT, threaded=True)
