# import os
# import platform
import sys
import logging
from pathlib import Path
from urllib.parse import urlparse
from bluecatipreg import options
from bluecatipreg.bluecat_utils import add_bluecat_ipreg, delete_bluecat_ipreg
from logging.handlers import RotatingFileHandler
import logging.handlers as handlers


LOG = logging.getLogger(__name__)

LOG_DIR = "/var/log/bluecat"
LOG_FILE = "blucat.log"
ROTATING_FILE_HANDLER_MAXBYTES = 10 * 1000 * 1000  # 10 mbytes
ROTATING_FILE_HANDLER_BACKUPCOUNT = 5

Path(LOG_DIR).mkdir(parents=True, exist_ok=True)

stdout_handler = logging.StreamHandler(sys.stdout)
file_handler = RotatingFileHandler(
    filename=f"{LOG_DIR}/{LOG_FILE}",
    maxBytes=ROTATING_FILE_HANDLER_MAXBYTES,
    backupCount=ROTATING_FILE_HANDLER_BACKUPCOUNT,
)

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    handlers=[file_handler, stdout_handler],
)


def is_valid_url(url):
    try:
        parsed = urlparse(url)
        if parsed.scheme in ("http", "https") and bool(parsed.netloc):
            return all([parsed.scheme, parsed.netloc])
        else:
            return False
    except ValueError:
        return False

def main():
    arg = options.parse()
    url = is_valid_url(arg.urlpath)
    if url:
        if arg.subparser == "add":
            add_bluecat_ipreg(arg.urlpath, arg.username, arg.password,
            arg.name, arg.fqdn, arg.ipaddressv4, arg.configuration,
            arg.network, arg.domain, arg.contact, arg.comment
            )
            LOG.info(f"Host {arg.fqdn} and IP {arg.ipaddressv4} has been registered successfully")
        if arg.subparser == "delete":
            delete_bluecat_ipreg(
            arg.urlpath, arg.username, arg.password,
            arg.ipaddressv4, arg.configuration
            )
            LOG.info(f"IP {arg.ipaddressv4} has been unregistered successfully")
    else:
        LOG.error("Provided URL is incorrect")

if __name__ == "__main__":
    main()
