#coding=utf-8

import json
from config 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 aliyunsdkvpc.request.v20160428.AllocateEipAddressRequest import AllocateEipAddressRequest
from aliyunsdkvpc.request.v20160428.DescribeEipAddressesRequest import DescribeEipAddressesRequest
from aliyunsdkvpc.request.v20160428.UnassociateEipAddressRequest import UnassociateEipAddressRequest
from aliyunsdkvpc.request.v20160428.AssociateEipAddressRequest import AssociateEipAddressRequest
from aliyunsdkvpc.request.v20160428.ReleaseEipAddressRequest import ReleaseEipAddressRequest
from aliyunsdkvpc.request.v20160428.ModifyEipAddressAttributeRequest import ModifyEipAddressAttributeRequest
import aliyunsdkcore
import time




class AliyunEip(object):
 
    def __init__(self, instanceid, region, *eipid):
        self.client = AcsClient(decodestr(Config.accessKeyId), decodestr(Config.accessSecret), region)
        self.instanceid = instanceid 
        if eipid:
            self.eipid = eipid[0]
        else:
            self.eipid = 0
        self.bandwidth = "1"
        
    # create EIP 
    def allocateEip(self):
        self.request = AllocateEipAddressRequest()
        self.request.set_Bandwidth(self.bandwidth)
        self.request.set_InternetChargeType("PayByTraffic")
        return self.doAaction 
          
    # display EIP
    def describeEip(self):
        self.request = DescribeEipAddressesRequest()
        if self.eipid:
            self.request.set_AllocationId(self.eipid)
            return self.doAaction
        return
    
    # release EIP from vps
    def unassociateEip(self):
        self.request = UnassociateEipAddressRequest()
        self.request.set_AllocationId(self.eipid)
        self.request.set_InstanceId(self.instanceid)
        return self.doAaction
    
    # bonding EIP to vps
    def associateEip(self):
        self.request = AssociateEipAddressRequest()
        self.request.set_AllocationId(self.eipid)
        self.request.set_InstanceId(self.instanceid)
        return self.doAaction
    
    # release EIP
    def releaseEip(self):
        self.request = ReleaseEipAddressRequest()
        self.request.set_AllocationId(self.eipid)
        return self.doAaction
    
    # set EIP info 
    # test EIP name GTGJEIP
    def modifyEip(self):
        self.request = ModifyEipAddressAttributeRequest()
        self.request.set_Name(self.eipname)
        self.request.set_AllocationId(self.eipid)
        return self.doAaction

    @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'))
    
    def eipInfo(self):
        eipinfo = self.describeEip()
        d =  {}
        if eipinfo:
            for eip in eipinfo['EipAddresses']['EipAddress']:
                self.eipid = eip['AllocationId']
                ipaddr = eip['IpAddress']
                d['IpAddress'] = ipaddr
                if eip['InstanceType'] == 'EcsInstance':
                    d['isbonding'] = 1
                else:
                    d['isbonding'] = 0
        return d
    
    def run(self):
        try: 
            eipinfo = self.eipInfo()
            sourceip = eipinfo.get('IpAddress')
            if  eipinfo.get('IpAddress'):
                if eipinfo['isbonding']:
                    self.unassociateEip()
                isbond = self.eipInfo().get('isbonding')
                while isbond:
                    isbond = self.eipInfo().get('isbonding')
                    time.sleep(0.5)              
                self.releaseEip()
            iseipexists = self.eipInfo().get(self.eipid)
            while iseipexists:
                iseipexists = self.eipInfo().get(self.eipid)
                time.sleep(0.5)
            neweip = self.allocateEip()
            self.eipid = neweip["AllocationId"]
            #self.modifyEip() 
            self.associateEip()    
            eipinfo = self.eipInfo()
            _neweip = eipinfo['IpAddress']
            print("replace ip success.")
            return {"status":"success", "sourceip": sourceip, "neweip": _neweip}
        except aliyunsdkcore.acs_exception.exceptions.ServerException as  e:
            return {"ERROR": str(e)}
       # except:
       #     return  {"status":"false"} 
         
         
#print(AliyunEip('cn-shenzhen').unassociateEip())
if __name__ == "__main__":
    #instance = (AliyunEip('i-wz9dzuvasloqyryn6xod', "cn-hangzhou", 'eip-wz94nj3izkmakzuf3r254'))
    instance = (AliyunEip('i-bp11ah3f4dtxjezay2oo', "cn-hangzhou", ''))
    print(instance.run())

    # print(instance.allocateEip())
