# Copyright 3D Control Systems, Inc. All Rights Reserved 2017-2019.

# Built in San Francisco.

# This software is distributed under a commercial license for personal,
# educational, corporate or any other use.
# The software as a whole or any parts of it is prohibited for distribution or
# use without obtaining a license from 3D Control Systems, Inc.

# All software licenses are subject to the 3DPrinterOS terms of use
# (available at https://www.3dprinteros.com/terms-and-conditions/),
# and privacy policy (available at https://www.3dprinteros.com/privacy-policy/)

import logging


try:

    # pylint: disable=import-error
    import win32print
except ImportError:
    logging.getLogger('WinDriverDetector').warning('No win32print installed')
    win32print = None

import config
from usb_detect import BaseDetector


class WinDriverDetector(BaseDetector):

    ENUM_LEVEL = 1 # winapi constant
    
    def __init__(self, _):
        self.logger = logging.getLogger(self.__class__.__name__)

    def get_printers_list(self):
        printers_list = []
        if win32print:
            flag = 2 #TODO check all of above
            try:
                win_tuple_of_tuple_printers = win32print.EnumPrinters(flag, None, self.ENUM_LEVEL)
            except Exception as e:
                self.logger.exception('MS Windows printer detection error:')
            else:
                self.logger.debug(win_tuple_of_tuple_printers)
                if win_tuple_of_tuple_printers:
                    for printer_tuple in win_tuple_of_tuple_printers:
                        if len(printer_tuple) > 2:
                            printer_name = printer_tuple[2] 
                            if printer_name in printers_list:
                                self.logger.warning(f'Duplicate printer name: {printer_name}')
                            printers_list.append(printer_name)
            if not printers_list and config.get_settings().get('win_printer_default_detection'):
                try:
                    printers_list = [win32print.GetDefaultPrinter()]
                except Exception as e:
                    self.logger.exception('MS Windows printer detection error:')
        return printers_list
