#!/usr/bin/python
# -*- coding: UTF-8 -*-

import subprocess

_services={}

_services['b2safe']=['b2safe_version','irods_version']
_services['gitlab']=['gitlab_version']
_services['svmon']=['spring_version','angular_version']
_services['b2access']=['b2access_unity']
_services['b2find']=['b2find_version','ckan_version']
_services['b2handle']=['handle_server','epic_version']
_services['b2drop']=['nextcloud_version']
_services['dpmt']=['plone']
_services['eudat_website']=['drupal_version']
_services['b2gether']=['b2gether_version']
_services['gocdb']=['creg_version']
_services['b2access']=['unity_version']
_services['svmon_client']=['client_version']

_rpm_packages={}
_rpm_packages['b2safe_version']='b2safe'
_rpm_packages['irods_version']='irods-icat'

_tags={}
_tags['svmon']=['3.1','1.7']

def in_service_list(service_type):
    #print(type(service_type))
    #print _services.has_key(service_type)
    if service_type == None or service_type == "" or isinstance(service_type,str) == False:
        print("The service type argument should be a non-empty string")
        exit(1)
    if service_type in _services.keys():
        return True
    else:
        print("Your service type is unsupported. Please type --list-service-type see supported services.")

def get_service_name(service_type):
    if service_type == None or service_type == "" or isinstance(service_type,str) == False:
        print("The service type argument should be a non-empty string")
        exit(1)
    if in_service_list(service_type):
        return _services.get(service_type)
    return []


def get_service_tag(service_type):
    if service_type == None or service_type == "" or isinstance(service_type,str) == False:
        print("The service type argument should be a non-empty string")
        exit(1)
    if in_service_list(service_type) == False:
        print("The service type is currently unsupported in svmon client")
        exit(1)

    tags=[]
    if service_type == "svmon_client":
        tmp = subprocess.Popen('pip show svmon-client', shell=True, stdout = subprocess.PIPE)
        tmp = subprocess.Popen('grep Version', shell = True, stdin=tmp.stdout, stdout = subprocess.PIPE)
        tmp = tmp.communicate()
        tmp=tmp[0]
        ltmp=tmp.split(':')
        if ltmp == None or len(ltmp) < 2:
            print("SVMON client can not be resolved, please check for installation")
            exit(1)
        ltmp=ltmp[1]
        ltmp.replace("\n","")
        ltmp.replace(" ", "")

        if ltmp == "":
            print("the version of svmon client can not resolved. Please check installation of svmon client")
            exit(1)
        tags.append(ltmp)
        return tags
    elif service_type == "gitlab":
        #tags.append("ce15") #currently for test
        tmp = get_version_by_rpm_packages("gitlab", 0 , 1)
        if tmp == "":
            print("no gitlab version can be resolved")
            exit(1)
        tags.append(tmp)
        return tags
    elif service_type == "b2safe":
        tmp=get_version_by_rpm_packages("b2safe")
        if tmp == "":
            print("no b2safe version can be resolved")
            exit(1)
        tags.append(tmp)
        tmp=get_version_by_rpm_packages("irods-icat")
        if tmp == "":
            print("no icat version can be resolved")
            exit(1)
        tags.append(tmp)
        return tags







# for package version that can be accessed via rpm management
def get_version_by_rpm_packages(software,start=0,end=0):
    if isinstance(software,str)  == False or software == "" or software == None:
        print("software name should be a non-empty string")
        exit(1)
    if isinstance(start,int) == False or isinstance(end, int) == False:
        print("The input of indices should be integers to fetch correct version,")
        exit(1)
    tmp = subprocess.Popen("rpm -qa", shell=True, stdout=subprocess.PIPE)
    tmp = subprocess.Popen('grep ' + software, shell=True, stdin=tmp.stdout, stdout=subprocess.PIPE)
    tmp = tmp.communicate()
    tmp = tmp[0]
    if  tmp == None or tmp == "":
        print("no rpm packages can be found for " + software)
        exit(1)
    ind=tmp.find(software)
    ind=ind+len(software)
    ltmp=tmp[ind+1:len(tmp)].split('-')

    if len(ltmp) > end:
        if start == end:
            return ltmp[start]
        elif start < end:
            res=""
            for i in range(start,end+1):
                res=res+ltmp[i]
            return res
        else:
            print("The start index should be smaller than end index for a correct rpm package resolver")
    else:
        print(software +" version not resolved")
        exit(1)



if __name__ == "__main__":
    print(in_service_list("aa"))
   # print(get_rpm("vim"))
    print(get_service_version_by_name("mariadb-client"))
   # print(get_service_version_by_name("gitlab"))
    #print(get_service_version_by_name("irods_version"))
    
