#!/usr/bin/python
#coding: utf-8  
#Author: asher
#Date: 2017/10/20
#Purpose: get dell server info from api.dell.com

import ConfigParser
import time
import datetime
import requests
import fileinput
import sys
import os
import re
import Queue
from multiprocessing import Pool
import threading
import codecs
reload(sys)
#sys.setdefaultencoding( "utf-8" )
sys.setdefaultencoding( "GB2312" )
import json


#fileName = sys.argv[1]
def gereneData():
    """
    将通用的一些数据读取放在一个函数里。不再每个函数里去写一遍了。
    """
    global apikey,stgfile,newfile,alljson,bigdicts

    fileName = os.path.abspath(__file__)
    binPath = os.path.dirname(os.path.realpath(__file__))
    basePath = os.path.dirname(binPath)
    confPath = basePath + '/config/'
    conf = ConfigParser.ConfigParser()
    conf.read("%s/dell.ini" % confPath)
    #####

    apikey = conf.get("dell","apikey")
    alljson = conf.get("dell","alljson")

    ####dell api
    stgfile = conf.get("dell","stgfile")
    newfile = conf.get("dell","newfile")

def getDellExpires(stg):
    """
    此函数将返回一个字典，有服务器的型号、出厂时间，过报时间，服务类型、还有剩余多少天在报
    这个过报时间当然是以查询时候的时间去计算的。

    """
    ##获取全局变量
    gereneData()

    dicts = {}
    payload = {"ID":""}
    payload['ID'] = stg


    api_url = 'https://sandbox.api.dell.com/support/assetinfo/v4/getassetwarranty'
    headers = {"Content-Type":"application/x-www-form-urlencoded",
                "apikey":"%s" % apikey,
                "accept":"application/json"}
    try:
        r = requests.post(api_url, headers=headers, data=payload).json()
        StartDate = r['AssetWarrantyResponse'][0]['AssetEntitlementData'][0]['StartDate']
        MachineDescription = r['AssetWarrantyResponse'][0]['AssetHeaderData']['MachineDescription']
        ServiceLevelDescription = r['AssetWarrantyResponse'][0]['AssetEntitlementData'][0]['ServiceLevelDescription']
        EndDate = r['AssetWarrantyResponse'][0]['AssetEntitlementData'][0]['EndDate']
        if MachineDescription:
            dicts['MachineDescription'] = MachineDescription
        else:
            dicts['MachineDescription'] = 'None'

        if EndDate:
            ##计算在保时间
            ###get warranty time
            timestg = EndDate.split('T')
            expiretime = ' '.join(timestg)
            dicts['EndDate'] = expiretime
            nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            expire1 = datetime.datetime.strptime(expiretime,"%Y-%m-%d %H:%M:%S")
            nowtime1 = datetime.datetime.strptime(nowtime,"%Y-%m-%d %H:%M:%S")
            remaintime = str(expire1 - nowtime1)
            avlTime  =  remaintime.split('days')[0]
            dicts['RemainDays'] = avlTime
        else:
            dicts['EndDate'] = 'None'


        if ServiceLevelDescription:
            dicts['ServiceLevelDescription'] = ServiceLevelDescription
        else:
            dicts['ServiceLevelDescription'] = 'None'

        if StartDate:
            timestg = StartDate.split('T')
            starttime = ' '.join(timestg)
            dicts['StartDate'] = starttime
        else:
            dicts['StartDate'] = 'None'

        return dicts
    except:
        ##if stg is wrong,  return nothing
        pass

def doGetDellExpires(stg):
    #stg1 = '7TQMKY1'
    if getDellExpires(stg):
        bigdicts[stg] = getDellExpires(stg)
    #if Adicts:
    #    print  Adicts['StartDate']
    #    print  Adicts['EndDate']
    #    print  Adicts['RemainDays']
    #    print  Adicts

    
def writefile(stgfile,newfile,bigdicts):
    """
    通过stgfile是ip,服务器型号,stg这个格式将从dell api获取到的保修信息写入这个文件
    """
    with open(newfile,'w') as ff:
        with open(stgfile,'r') as f:
            for fi in f.readlines():
                lines = fi.split(',')
                if len(lines) < 5:
                    print lines + ' is ' + ' wrong'
                    continue
                stg = lines[2]
                if  bigdicts[stg]:
                    if bigdicts[stg]['EndDate']:
                        endtime = bigdicts[stg]['EndDate']
                    else:
                        endtime = 'no'
                    if bigdicts[stg]['StartDate']:
                        starttime = bigdicts[stg]['StartDate']
                    else:
                        starttime = 'no'
                    if  bigdicts[stg]['RemainDays']:
                        RemainDays = bigdicts[stg]['RemainDays']
                    else:
                        RemainDays = 'no'
                    lines.insert(3,RemainDays)
                    lines.insert(3,endtime)
                    lines.insert(3,starttime)
                    newlines = ','.join(lines)
                    ff.write("%s\n" % newlines.strip().encode("GB2312"))

def writedict2json(bigdicts,alljson):
    """
    将字典写入json
    bigdicts,alljson
    """
    gereneData()
    #print json.dumps(bigdicts,sort_keys=True, indent=4)
    #print json.dumps(bigdicts,indent=4)
#    print dicts
    olddicts = {}
    newdicts = {}
    if os.path.isfile(alljson):
        ff = open(alljson)
        olddicts = json.load(ff)
    #print bigdicts
    for k in olddicts.keys():
        if olddicts[k]:
            pass
        else:
            del olddicts[k]
#    print olddicts
    #合并字典，将重复的给拿掉
    #newdicts = dict(olddicts, **bigdicts)
    newdicts.update(olddicts)
    for k in bigdicts.keys():
        if bigdicts[k]:
            pass
        else:
            del bigdicts[k]

            

    newdicts.update(bigdicts)
#    print newdicts

    with open(alljson,'w') as f:
        f.write(json.dumps(newdicts,indent=8))
        f.write('\n')
    
def multiGetinfo():
    """
    并发获取信息
    """
    ###获取全局变量
    gereneData()

    stgs = []
    global bigdicts
    bigdicts = {}
    #172.30.211.49,PowerEdge R620,36LMKY1,DiskNU:5,RAIDLOG:OK,IDRACLOG:OK
    #172.30.187.84,PowerEdge R620,9THDZX1,10.131.174.11,开放,game1,完美国际,无锡国际,0|Failed|558.38 GB|HDD|SEAGATE|S0M0708J,IDRACLOG:OK
    ###读取旧的信息，不再重复去调用dell api
    olddicts = {}
    if os.path.isfile(alljson):
        ff = open(alljson)
        olddicts = json.load(ff)
    for k in olddicts.keys():
        if olddicts[k]:
            pass
            #print olddicts[k]
        else:
            del olddicts[k]
    stgkeys = olddicts.keys()

    with open(stgfile,'r') as f:
        for fi in f.readlines():
            lines = fi.split(',')
            if len(lines) < 5:
                print fi + ' is ' + ' wrong'
                continue
            stg = fi.split(',')[2]
            if stg in stgkeys:
                if olddicts[stg]:
                    bigdicts[stg] = olddicts[stg]
                else:
                    bigdicts[stg] = {}
                    doGetDellExpires(stg)
            else:
                print stg
                bigdicts[stg] = {}
                doGetDellExpires(stg)
#            T_threads.append(threading.Thread(target=doGetDellExpires,args=(stg,)))
#        for i in range(len(T_threads)):
#            T_threads[i].start()

#    print bigdicts
#    writefile(stgfile,newfile,bigdicts)
    writedict2json(bigdicts,alljson)


if __name__ == '__main__':
#    stg1 = '6K98JY1'
##    stg1 = '7TQMKY1'
#    Adicts = getDellExpires(stg1)
#    if Adicts:
#        print  Adicts['StartDate']
#        print  Adicts['EndDate']
#        print  Adicts['RemainDays']
#        print  Adicts
#    else:
#        print 'error'
#
#    gereneData()
    multiGetinfo()
