"""
FB Logic Class
Version 0.1

This file is generated by FB Devkit. Should add FB logic here.
"""
import logging
from spidr_communicator import ParamInput, ParamOutput

class TemplateAPIRESTful:

    def __init__(self, name: str, param_input: ParamInput, param_output: ParamOutput):
        """
        This function will be called by main.py, is the initial method of this FB
        If you have a input parameter name "newvalue", you can get it by self.param_input.newvalue
        If you want to set a output parameter name "status", you can set it by self.param_output.status = "Good"
        """
        self.name = name
        self.param_input = param_input
        self.param_output = param_output
        
        # Here is the second layer of parameter analysis, which can be customized

    def run(self):
        """
        This function will be called by main.py, is the main method of this FB
        """
        logging.info("Run function start")
        import requests
        import json
        from requests import RequestException

        result = None
        timeout = None
        if self.param_input.timeout:
            timeout = self.param_input.timeout
        try:
            if self.param_input.httpCommand == "GET":
                result = requests.get(self.param_input.URL, self.param_input.sendData, timeout=timeout)
            elif self.param_input.httpCommand == "POST":
                result = requests.post(self.param_input.URL, self.param_input.sendData, timeout=timeout)
            elif self.param_input.httpCommand == "PUT":
                result = requests.put(self.param_input.URL, self.param_input.sendData, timeout=timeout)
            elif self.param_input.httpCommand == "DELETE":
                result = requests.delete(self.param_input.URL, self.param_input.sendData, timeout=timeout)
            self.param_output.status = "Good"
            self.param_output.recvData = json.loads(result.text)
        except RequestException as e:
            logging.exception(e)
            self.param_output.status = "Bad"

    def is_state_turn_to_fail(self):
        """
        This method will be called by main.py
        It's a hook in running block before send machine state success, has the opportunity to set machine state as fail
        """
        return False

    def is_state_turn_to_success(self, exception):
        """
        This method will be called by main.py
        It's a hook in exception handling block before send machine state fail, has the opportunity to set machine state
        as success
        """
        return True
