#!/usr/bin/env python3
from __future__ import print_function

import re
from datetime import timedelta
import argparse
import unificontrol

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

import math

SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
SPREADSHEET_ID = '18v8v6hoZTjahWhvyxRldmbdVlqAyKLa2HDINJJfTgKA'

class Client:
  def __init__(self, hostname, address, macAddress, k8s):
    self.hostname = hostname
    self.address = address
    self.macAddress = macAddress
    self.k8s = k8s

  def formatYamlEntry(self):
    entry = "    {} {} # {}\n".format(self.hostname, self.address, self.macAddress)
    return entry

def getClientsSheets(args):
  print("SheetID: {}".format(args.sheetid))
  c = Client(hostname="tesseract", address="192.168.1.87", macAddress="00:00:00:AA:BB:CC", k8s=False)
  return c

def getClientsUnifi(args):
  UNIFI_USER='robot'
  UNIFI_PASS='fguohsfogj910A'
  udm = unificontrol.UnifiClient(host='192.168.1.1', username=UNIFI_USER, password=UNIFI_PASS, site='Default')
  for mac in udm.list_guests():
    print(mac)
  c = Client(hostname="gondor", address="192.168.1.9", macAddress="00:00:00:AA:BB:CC", k8s=False)
  return c

def getClientsPihole(args):
  c = Client(hostname="morgul", address="192.168.1.1", macAddress="00:00:00:AA:BB:CC", k8s=False)
  return c



def buildGoogleCredentials(args):
  creds = None
  if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
  if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
      creds.refresh(Request())
    else:
      flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
      creds = flow.run_local_server(port=0)
    with open('token.json', 'w') as token:
      token.write(creds.to_json())
  return creds

def main():
  parser = argparse.ArgumentParser()


  parser.add_argument("--pihole", required=False, help="Render k8s configMap for pihole use", action='store_true')
  parser.add_argument("--pifile", required=False, help="Filename to store rendered yaml", type=str)

  parser.add_argument("--unifi",   required=False, help="Sync client addresses to unifi controller", action='store_true')
  parser.add_argument("--hostname", required=False, help="Unifi Hostname", type=str, default='192.168.1.1')
  parser.add_argument("--username", required=False, help="Unifi Username", type=str, default='admin')
  parser.add_argument("--password", required=False, help="Unifi Password", type=str, default='admin')

  parser.add_argument("--sheet", required=False, help="Sync client address to Google Sheet", action='store_true')
  parser.add_argument("--sheetid", required=False, help="Google Sheet ID to read from", type=str)

  parser.add_argument("--readfrom", required=True, help="Which datasource to read from (unifi, pihole, sheets)", type=str, action='append')
  parser.add_argument("--writeto", required=True, help="Which datasource to write to (unifi, pihole, sheets, stdout)", type=str, action='append')


  clients = []
  args = parser.parse_args()
  for read in args.readfrom:
    results = []
    print("Reading from {}".format(read))
    if read == "sheets":
      results.append(getClientsSheets(args))

    if read == "unifi":
      results.append(getClientsUnifi(args))
    
    if read == "pihole":
      results.append(getClientsPihole(args))

    for result in results:
      for c in clients:
        print("{}".format(c.address))
      print("Merging {} results from {} into Clients".format(result.hostname, read))
      clients.append(result)

  print("Len: {}".format(len(clients)))
  for c in clients:
    print("Clients: {} {} {}".format(c.address, c.hostname, c.macAddress))

  for write in args.writeto:
    print("Writing to {}".format(write))
    for c in clients:
      print("Discovered Client: {}".format(c.hostname))
      if write == "pihole":
        print(c.formatYamlEntry)
      



if __name__ == "__main__":
  main()
