#!/usr/bin/env python3
#-*- coding: UTF-8 -*-

"""
Description: automation test common python keywords
Author: Wu Wei
"""

import os
import json
import requests
from robot.libraries.BuiltIn import BuiltIn
from collections import Counter


class public_python_keywords(object):

    def __init__(self):
	    pass

    @classmethod
    def fetch_txt_vars(self,file="H:\\rfs_scripts\\vars.txt"):

        vars = {}

        f = open(file, "r")
        line = f.readline().rstrip('\n')

        while line:
            if '|' in line:
                line_list = line.split('|')
                vars[line_list[0]]=line_list[1]
                line = f.readline().rstrip('\n')

        return vars

    def fetch_json_vars(self,file="H:\\rfs_scripts\\vars.json"):
    
        with open(file,'r',encoding='utf-8') as fp:
            vars = json.load(fp)
    
        return vars
        
    def fetch_word_counter(self,data=None,word=None):
        #usage example:
        #${result}    Fetch Word Counter    data=${data}    word=test
    
        if data is None:
            raise Exception("------please provide data------")
            
        if word is None:
            raise Exception("------please provide word------")
        
        counter_result=Counter(data)
        print(counter_result)
        
        count=counter_result[word]
        print(count)
        
        return count

    def get_data_by_list_remove(self,data=None,remove_list=None,**kwargs):
    
        if data is None:
            raise Exception("------please provide raw data------")
            
        if remove_list is None:
            raise Exception("------please provide remove list------")
            
        print("data is %s,\n remove_list is %s,\n" %(data,remove_list))
        
        data_list = []
        counter = len(data)
        
        for i in range(0,counter):
            print(data[i])
            if data[i] not in remove_list:
                line_list = data[i]
                print(line_list)
                data_list.append(line_list)
        
        print(data_list)
        return data_list
        
    def get_data_by_list_index_and_stepsize(self,data=None,index_value=0,stepsize=3,**kwargs):
    
        if data is None:
            raise Exception("------please provide raw data------")
            
        print("data is %s,\n index_value is %s,\n stepsize is %d\n" %(data,index_value,stepsize))
        
        data_list = []
        counter = len(data)
        
        for i in range(index_value,counter,stepsize):
            #print(data[i])
            line_list = data[i]
            #print(line_list)
            data_list.append(line_list)
        
        print(data_list)
        return data_list
            
    def generate_task_var_data(self,var_file=None,**kwargs):
        #usage example:
        #@{my_templateId}    Create List    abcdefg1    abcdefg2    abcdefg3    abcdefg4    abcdefg5
        #@{my_aniList}    Create List    01021753680    01021753672
        #Generate Task Var Data
        #...    var_file=C:\\yaoyao====\\my_vars.txt
        #...    templateId=${get_templateId}
        #...    taskName=ruby新任务ffffffffffffffffffffffffffffffffffffffffffffabc
        #...    robotNum=2
        #...    aniList=${my_aniList}
    
        key = str(kwargs.get("key",'task'))
        templateId = list(kwargs.get("templateId",['a6024192b6fe4f57895bed017a928325']))
        taskName = str(kwargs.get("taskName",'新'))    
        robotNum = int(kwargs.get("robotNum",1))
        aniList = list(kwargs.get("aniList",['00000000000']))

        print(var_file)
        print(key)
        print(templateId)   
        print(taskName)
        print(robotNum)
        print(aniList)
        
        cmd=''

        if var_file is None:
            raise Exception("var file doesn't exist, please check it")
            
        if os.path.exists(var_file):
            os.remove(var_file)
  
        for i in range(0,len(templateId)):
            j = i+1
            cmd = 'key=' + key + str(j) + '||templateId=' + templateId[i] + '|taskName=' + taskName + str(j)+ '|robotNum=' + str(robotNum) + '|aniList=' + str(aniList)
            print(cmd)
            with open(var_file,'a',encoding='utf-8') as f:
                if i!=len(templateId)-1:
                    f.write(cmd+'\n')
                else:
                    f.write(cmd)
        
    def create_task_dict(self,var_file=None,write_file=None,**kwargs):
        #usage example:
        #Create Task Dict    var_file=C:\\yaoyao====\\my_vars.txt    write_file=C:\\yaoyao====\\my_write_file.json
        
        if var_file is None:
            raise Exception("don't give var file, please check it")
        if write_file is None:
            raise Exception("don't give written file, please check it")
    
        value_dict = {}
        my_task_dict ={}
        
        key_list = []
        value_list = []
    
        f = open(var_file, "r", encoding='utf-8')
        lines = f.read()
        #print(lines)
        
        lines = lines.split('\n')        

        for line in lines:
            new_line = line.split('||')
    
            key = new_line[0].split('=')[1].replace('"',"").replace("'","")
            #print(key)
            
            key_list.append(key)
            
            values = new_line[1].split('|')
            #print(values)
                
            for value in values:           
                #print(value)
                item = value.split('=')
                if item[0] == 'templateId':
                    value_dict['templateId'] = item[1].replace("'", '').replace('"', '')
                if item[0] == 'taskName':
                    value_dict['taskName'] = item[1].replace("'", '').replace('"', '')
                if item[0] == 'robotNum':
                    value_dict['robotNum'] = int(item[1].replace("'", '').replace('"', ''))                   
                if item[0] == 'aniList':
                    temp=item[1].replace('\n', '').replace('\r', '').replace(' ', '').replace("[","").replace("]","").replace('"',"").replace("'","")                
                    temp_list=temp.split(',')
                    value_dict['aniList'] = temp_list
                if item[0] == 'timeType':
                    value_dict['timeType'] = int(item[1].replace("'", '').replace('"', ''))
                if item[0] == 'lineType':
                    value_dict['lineType'] = int(item[1].replace("'", '').replace('"', ''))
                if item[0] == 'priority':
                    value_dict['priority'] = int(item[1].replace("'", '').replace('"', ''))
                if item[0] == 'telephoneRule':
                    value_dict['telephoneRule'] = int(item[1].replace("'", '').replace('"', ''))
                if item[0] == 'retryFlag':
                    value_dict['retryFlag'] = int(item[1].replace("'", '').replace('"', ''))
                if item[0] == 'numberHide':
                    value_dict['numberHide'] = int(item[1].replace("'", '').replace('"', ''))
                    
            #print(value_dict)
            new_value_dict = value_dict.copy()
            value_list.append(new_value_dict)
        
        #print(key_list)        
        #print(value_list)   

        my_task_dict = dict(zip(key_list,value_list))       
        #print("-------------------------------")        
        #print(my_task_dict)

        with open(write_file,'w',encoding='utf-8') as f:
            written_info=json.dumps(my_task_dict,ensure_ascii=False)
            f.write(written_info)
                     
    def fetch_token(self,basic_url="http://82.156.243.104:8000/api/6.0.0/",username=None,**kwargs):
        #usage example:
        #${get_token}    Fetch Token    basic_url=http://82.156.243.104:8000/api/6.0.0/    username=${gbl_vars}[email]
    
        if username is not None:
            get_apikey_and_apisecret_url = basic_url + 'consumers/' + username  
        #print(get_apikey_and_apisecret_url)
    
        response = requests.get(url=get_apikey_and_apisecret_url)
        response.raise_for_status() 


        resp_json = json.loads(response.text)
        #print(resp_json)

        get_apiKey = resp_json["content"][0]["apiKey"]
        get_apiSecret = resp_json["content"][0]["apiSecret"]
        #print(get_apiKey)
        #print(get_apiSecret)
        
        #token url
        token_url = basic_url + 'tokens?apiKey=' + get_apiKey + '&apiSecret=' + get_apiSecret
        #print(token_url)
       
        response = requests.get(url=token_url)
        response.raise_for_status() 
        resp_json = json.loads(response.text)
        print(resp_json)        

        get_access_token = resp_json["content"]["access_token"]
        #print(get_access_token)     

        return get_access_token
        
    def fetch_companyId(self,basic_url="http://82.156.243.104:8000/api/6.0.0/",username=None,password=None,**kwargs):
        #usage example:
        #${headers}    Create Dictionary    Content-Type=application/json
        #${datas}    Create Dictionary    userPassWord=${gbl_vars}[password]
        #${get_companyId}    Fetch CompanyId    basic_url=http://82.156.243.104:8000/api/6.0.0/    username=${gbl_vars}[email]    password=${gbl_vars}[password]    headers=${headers}    datas=${datas}

        headers = dict(kwargs.get("headers",dict()))
        datas = dict(kwargs.get("datas",dict()))
        print(headers)
        print(datas)

        if username is not None:
            get_companyId_url = basic_url + 'reference-icall-users/' + username  
        print(get_companyId_url)
        response = requests.get(url=get_companyId_url,headers=headers,data=json.dumps(datas))
        response.raise_for_status() 
        resp_json = json.loads(response.text)
        print(resp_json)
                
        if resp_json["code"]!=200:
            raise Exception("status code isn't 200")
        
        get_companyId = resp_json["content"]["companyId"]
        print(get_companyId)   

        return get_companyId
        
    def get_json_templateId_response(self,basic_url="http://82.156.243.104:8000/api/6.0.0/",companyId=None,**kwargs):

        headers = dict(kwargs.get("headers",dict()))
        print(headers)

        if companyId is not None:
            get_templateId_url = basic_url + 'companies/' + companyId + '/templates'
        print(get_templateId_url)
        response = requests.get(url=get_templateId_url,headers=headers)
        response.raise_for_status() 
        resp_json = json.loads(response.text)
        return resp_json
                
    def create_task_by_file(self,basic_url="http://82.156.243.104:8000/api/6.0.0/",companyId=None,file=None,**kwargs):

        #usage example:
        #${headers}    Create Dictionary    Authorization=Bearer ${get_token}    Content-Type=application/json
        #Create Task By File    basic_url=http://82.156.243.104:8000/api/6.0.0/    companyId=${get_companyId}    headers=${headers}    file=C:\\yaoyao====\\my_write_file.json
        
        headers = dict(kwargs.get("headers",dict()))
        print(headers)
        
        if companyId is not None:
            get_create_task_url = basic_url + 'companies/' + companyId + '/tasks'
        print(get_create_task_url)
            
        if file is not None:
            result = json.load(open(file,'r',encoding='utf-8'))
            keys = result.keys()
            #print(keys)

        for key in keys:
            print(result[key])
            print("------------")
            print(json.dumps(result[key],ensure_ascii=False))
            #response = requests.post(url=get_create_task_url,headers=headers,data=json.dumps(result[key],ensure_ascii=False))
            response = requests.post(url=get_create_task_url,headers=headers,data=json.dumps(result[key]))
            response.raise_for_status() 
            resp_json = json.loads(response.text)
            print(resp_json)
            
    def return_driver_props(self):
        print("---------abc-------------")
        seLib = BuiltIn().get_library_instance('SeleniumLibrary')
    
        # the driver is instantiated in the SeleniumLibrary, but not provided publicly, thus accessing it through this py code 
        remote_url = seLib.driver.command_executor._url  # for local instance, this is a value in the form 'http://localhost:57856'
        session_id = seLib.driver.session_id
    
        return remote_url, session_id
        
    def set_driver_session_id(self,sesion_id):
        """ Sets the sessoin_id of the current driver insance to the provided one. """
        seLib = BuiltIn().get_library_instance('SeleniumLibrary')
    
        if seLib.driver.session_id != sesion_id:  # this is pretty much guaranteed to be the case
            seLib.driver.close()  # this closes the session's window
            seLib.driver.quit()   # for remote connections (like ours), this deletes the session, but doesn't stop the SE
    
        #set to the session that's already running
        seLib.driver.session_id = sesion_id 

if __name__ == '__main__':
    
    b=globalvars().fetch_vars()
    print(b)
