#import appdaemon.plugins.hass.hassapi as hass
import requests
from requests.structures import CaseInsensitiveDict
import json

# References
# https://www.geeksforgeeks.org/python-requests-post-request-with-headers-and-body/
# https://www.geeksforgeeks.org/response-status_code-python-requests/
# https://reqbin.com/post-online


#
# Hello World App
#
# Args:
#

class Opengate(): #hass.Hass):

  def initialize(self):
    self.log("Hello from AppDaemon")
    self.log("You are now ready to run Apps!")
    self.listen_state(self.OpenTheGate, "input_boolean.trigger", new = "on")
    #self.listen_state(self.OpenTheGate, "zone.front_gate", new = "1")
    self.listen_event(self.OpenTheGate, "app_daemon_open_front_gate")
  def log(self,outputtext):
    print(outputtext)
  # Our callback function will be called by the scheduler every day at 7pm
#  def OpenTheGate(self, entity, attribute, old, new, kwargs):
  def OpenTheGate(self): ###, event_name, data, kwargs):
    # Open the gate!
    self.log("Open gate triggered")
    #self.log("event_name id {}".format(event_name))
    #self.log("data {}".format(data))

    #return

    # initial login
    url = "https://summitcontrol.com"
    rest = "/SnapApi/index.php/auth/login"

    headers = CaseInsensitiveDict()
    headers["Client-Service"] = "frontend-client"
    headers["Auth-Key"] = "simplerestapi"
    headers["Content-Type"] = "application/json;charset=UTF-8"
    headers["Connection"] = "Keep-Alive"
    headers["Accept-Encoding"] = "gzip"
    headers["User-Agent"] = "okhttp/3.12.1"
    

    data = {
      ###"client_id":"user_name","client_secret":"password","grant_type":"client_credentials"
      "client_id":"MMHOAReichbach","client_secret":"4rj75nbu","grant_type":"client_credentials"
    }

    forReal = True

    # send request for initial login
    if forReal:
      response = requests.post(url + rest, headers=headers, json=data)
      print(url+rest)
      print(headers)
      print(data)
    else:
      self.log("Faking it!")
      response =  {
        'status_code': '200', 
        'json': {'access_token': '8450ad8ac6e002071b95bf9b53117e68bef6d6e4', 'expires_in': 1209600, 'token_type': 'Bearer', 'scope': None, 'status': 200, 'message': 'Successfully login'}
      }
        

    self.log("Login headers {}".format(headers))
    self.log("Login Request Data {}".format(data))
    self.log("Login Response {}".format(response))
    self.log("Login JSON Data {}".format(response.json()))

    # fix access token
    accessToken = response.json()['access_token']
    
    self.log("accessToken {}".format(accessToken))

    headers['Authorization'] = 'Bearer ' + accessToken

    if False:

      # User type?
      rest = "/SnapApi/index.php/user/userType"

      data = {}

      if forReal:
        response = requests.post(url + rest, headers=headers, json=data)
      else:
        response = {"none": "none"}

      self.log("User headers {}".format(headers))
      self.log("User Request Data {}".format(data))
      self.log("User Response {}".format(response))
      self.log("User JSON Data {}".format(response.json()))

    if response.status_code != 200:
      self.log("Bad response, exiting")
      return


    # build open gate request
    rest = "/SnapApi/index.php/Actions/Open"

    
    data = {
      "deviceCode":"code_641cb73fcdec23.09325833","deviceID":"12310","relay":"1"
    }

    if forReal:
      response = requests.post(url + rest, headers=headers, json=data)
    else:
      response = {"none": "none"}

    self.log("Open headers {}".format(headers))
    self.log("Open Request Data {}".format(data))
    self.log("Open Response {}".format(response))
    self.log("Open JSON Data {}".format(response.json()))

    if response.status_code != 200:
      self.log("Bad open response, exiting")
      return

    #self.call_service("notify/mobile_app_sm_g975u", message = response.json()['message'])
    print(response.json())

o = Opengate()
o.OpenTheGate()
