#!/usr/bin/env python
#coding=utf-8
import json
import uuid
from config_hbgj import Config
from word_generater import decodestr
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkecs.request.v20140526.CreateInstanceRequest import CreateInstanceRequest
from aliyunsdkecs.request.v20140526.RunInstancesRequest import RunInstancesRequest
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.ModifyInstanceChargeTypeRequest import ModifyInstanceChargeTypeRequest
from aliyunsdkecs.request.v20140526.DeleteInstancesRequest import DeleteInstancesRequest

class AliyunECS(object):
    # if user=gtgj, only allowed ecs.t5-lc1m1.small for ecs type
    # set_DryRun(True) for debug
    # rlease instance api ModifyInstanceAutoReleaseTime   https://help.aliyun.com/document_detail/47576.html?spm=a2c4g.11186623.6.1191.66777c25Y5tDMN

    # request.set_ImageId("m-2ze9rkkcv9k4mi693nob")
    # request.set_InstanceType("ecs.t5-lc1m1.small")
    # request.set_InstanceName("proxy")
    # request.set_InternetChargeType("PayByTraffic")
    # request.set_InternetMaxBandwidthOut(1)
    # request.set_HostName("porxy")
    # request.set_Password("password3324!")
    # request.set_SystemDiskSize(40)
    # request.set_SystemDiskCategory("cloud_efficiency")
    # request.set_Description("proxy")
    # request.set_VSwitchId("vsw-2zeay6fvk4kq6dtvyk8nh")
    # request.set_InstanceChargeType("PostPaid") 
    """
    {
    	"InstanceId": "i-2zeat29qpyvlcfh6p17v",
    	"RequestId": "6D3573AF-B8BC-4679-BA62-F1CBDB25CC7D"
    }
    """


    '''
        for choice argments:
        InternetChargeType,  if instanceChargeType==Prepaid then InternetChargeType=PayByBandwidth else PayByTraffic
        InstanceChargeType # if InstanceChargeType==PrePaid then PeriodUnit=Month or InstanceChargeType=PostPaid
        InstanceCount
        Password
    '''

    '''static argments:
        ImageId
        InstanceType
        InstanceName
        InternetMaxBandwidthOut
        HostName
        SystemDiskSize
        SystemDiskCategory
        Description
        VSwitchId
    '''
    # {'RequestId': 'F67D0AE3-8B4A-4A06-88E1-AD037B8D2F3B', 'InstanceIdSets': {'InstanceIdSet': ['i-2ze7anzznp9keos3mzo2', 'i-2ze7anzznp9keos3mzo3']}, 'TradePrice': 53.2} 
    def __init__(self, user="gtgj", **CreateInfo):
        
        metadata = ["RegionId", "AutoReleaseTime", "InstanceCount"]
        self.CreateInfo = CreateInfo
        self.set_Region = self.CreateInfo.pop("set_Region")
        self.CreateInfo['set_InstanceType'] = "ecs.t5-lc1m1.small"
        self.CreateInfo['set_ImageId'] = "m-2ze9rkkcv9k4mi693nob"
        self.CreateInfo['set_InstanceName'] = "proxy"
        self.CreateInfo['set_InternetMaxBandwidthOut'] = 1
        self.CreateInfo['set_HostName'] = "proxy"
        self.CreateInfo['set_Description'] = "proxy"
        self.CreateInfo['set_SecurityGroupId'] = "sg-2ze4a0k1v1gsidwkez2c"
        self.CreateInfo['set_SystemDiskSize'] = 40
        self.CreateInfo['set_SystemDiskCategory'] = "cloud_efficiency"
        self.CreateInfo['set_VSwitchId'] = "vsw-2zeay6fvk4kq6dtvyk8nh"
        # if self.CreateInfo.get("set_InternetChargeType") == "Prepaid" and self.CreateInfo.get("set_InternetChargeType") == "PayByBandwidth" :
        if self.CreateInfo.get("set_InstanceChargeType") == "PrePaid":
             self.CreateInfo['set_PeriodUnit'] = "Month"
             self.CreateInfo['set_Period'] = 1
             self.CreateInfo['set_AutoRenewPeriod'] = 1
             self.CreateInfo['set_AutoRenew'] = True

             self.set_PayType = 1 # 1. PayByBandwidth  2.PayByTraffic
             
        else:
             self.PayType = 0 
        self.client = AcsClient(decodestr(Config.accessKeyId), decodestr(Config.accessSecret), self.set_Region)

    @property 
    def doAaction(self):
        self.request.set_accept_format('json')
        response = self.client.do_action_with_exception(self.request)
        return json.loads(str(response, encoding='utf-8')) 

    @property
    def CreateECSInstance(self):
        self.request = RunInstancesRequest()
        ecs_password = self.CreateInfo.get("Password")
        for k,v in self.CreateInfo.items():
            print("""self.request.%s("%s") """ % (k, v))
            exec("""self.request.%s("%s") """ % (k, v))
        self.request.set_ClientToken(uuid.uuid1())
        return self.doAaction

    # https://api.aliyun.com/?spm=a2c4g.11186623.2.9.78953290C6BExH#/?product=Ecs&api=DescribeInstances&params={}&tab=DEMO&lang=PYTHON
    def DescribeInstances(self, InstanceIds):
        self.request = DescribeInstancesRequest()
        self.request.set_PageSize(100)
        # InstanceIds ["i-2ze551ld3zvhp56r2504"]
        self.request.set_InstanceIds(InstanceIds)
        Data = self.doAaction
        InstancesInfo = []
        for instance in  Data['Instances']["Instance"]:
            PrivateIpAddress = instance['NetworkInterfaces']["NetworkInterface"][0]["PrimaryIpAddress"]
            PublicIpAddress = instance["PublicIpAddress"]["IpAddress"][0]
            InstanceId = instance["InstanceId"]
            InstanceChargeType = instance["InstanceChargeType"]
            InstancesInfo.append({'InstanceId':InstanceId, "PublicIpAddress": PublicIpAddress, "PrivateIpAddress":PrivateIpAddress, "InstanceChargeType":InstanceChargeType})
        return InstancesInfo
       
    def ReleaseInstances(self, InstanceIds):
        InstancesInfo = self.DescribeInstances(InstanceIds)
        PrePaidInstanceIds = [instance['InstanceId'] for instance in InstancesInfo if instance['InstanceChargeType'] == "PrePaid"]
        if PrePaidInstanceIds:
            self.PrePaid2PostPaid(PrePaidInstanceIds)
        self.request = DeleteInstancesRequest()
        self.request.set_Force(True)
        self.request.set_InstanceIds(InstanceIds)
        return self.doAaction
        

    def PrePaid2PostPaid(self, InstanceIds):
        self.request = ModifyInstanceChargeTypeRequest()
        self.request.set_InstanceChargeType("PostPaid")
        self.request.set_InstanceIds(InstanceIds)
        return self.doAaction
         

if __name__ == "__main__":
    #instance =  AliyunECS(set_Region="cn-beijing", set_InternetChargeType="PayByTraffic", set_InstanceChargeType="PostPaid", set_Password="Pass@123!", set_Amount=2)
    #instance =  AliyunECS(set_Region="cn-beijing", set_InternetChargeType="PayByBandwidth", set_InstanceChargeType="PrePaid", set_Password="Pass@123!", set_Amount=2)
    #print(instance.CreateECSInstance)
    
    #instance =  AliyunECS(set_Region="cn-beijing")
    #print(instance.DescribeInstances(["i-2ze551ld3zvhp56r2504", "i-2ze551ld3zvhp56r250e"]))
    
    instance =  AliyunECS(set_Region="cn-beijing")
    print(instance.ReleaseInstances(["i-2zefwbdpum6qmsl9yx6x","i-2zefwbdpum6qmsl9yx6y"]))       

#    def ModifyECSInstance():
#
#    def Run():
#        self.CreateInfo.get("InstancesCount") 
