# coding: utf-8
from flask import Flask, request
from flask import jsonify
import json
from InstanceID import privateIP2InstanceID
from EIPChanger import AliyunEip
from ECSCreater import AliyunECS
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    filename='logs/debug.log',
                    filemode='a')


app = Flask(__name__)
@app.route("/instaceid", methods=['POST'])
def getinstanceid():
    privateip = request.form['privateip']
    region=request.form['region']
    result = privateIP2InstanceID(privateip, region)
    return jsonify(result)


@app.route("/reseteip", methods=['POST'])
def reseteip():
    # ""
    #data = json.loads(request.get_data(as_text=True))
    privateip = request.form['privateip']
    region=request.form['region']
    d = privateIP2InstanceID(privateip,region) 
    instanceid = d['instanceid']
    if d.get('eipid'):
        eipid = d['eipid']
        runner = AliyunEip(instanceid, region, eipid)
    else:
        runner = AliyunEip(instanceid, region)
    data = runner.run()
    return jsonify(data)

@app.route("/createecs", methods=['POST'])
def createecs():
    # set_Region
    # set_InternetChargeType  PayByTraffic or PayByBandwidth
    # set_InstanceChargeType  PostPaid     or PrePaid
    # set_Password
    # set_Amount
    set_Region = request.form['set_Region']
    set_InternetChargeType = request.form['set_InternetChargeType']
    set_InstanceChargeType = request.form['set_InstanceChargeType']
    set_Password = request.form['set_Password']
    set_Amount = request.form['set_Amount']
    instance = AliyunECS(set_Region=set_Region, set_InternetChargeType=set_InternetChargeType, set_InstanceChargeType=set_InstanceChargeType, set_Password=set_Password, set_Amount=set_Amount)
    result = instance.CreateECSInstance
    return jsonify(result)

@app.route("/describeinstances", methods=['POST'])
def describeinstances():
    set_Region = request.form['set_Region']
    InstanceIds = eval(request.form['InstanceIds'])
    instance = AliyunECS(set_Region=set_Region)
    result = instance.DescribeInstances(InstanceIds)
    return jsonify(result)

@app.route("/releaseinstances", methods=['POST'])
def releaseinstances():
    set_Region = request.form['set_Region']
    InstanceIds = eval(request.form['InstanceIds'])
    instance = AliyunECS(set_Region=set_Region)
    result = instance.ReleaseInstances(InstanceIds)
    return jsonify(result)

if __name__ == "__main__":
    app.run(host="0.0.0.0")
