#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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 os
import sys

import platform

LIBRARIES_FOLDER = 'libraries'
APP_FOLDER = os.path.dirname(os.path.abspath(__file__))

def check_and_create_dirs(path):
    while path:
        path = os.path.dirname(path)
        if os.path.exists(path):
            break
        else:
            os.mkdir(path)

def get_libusb_path(lib):
    #logger = logging.getLogger(__name__)
    #logger.debug('Using: ' + lib)
    if sys.platform.startswith('win'):
        folder_name = "win"
        python_version = platform.architecture()[0]
        if '64' in python_version:
            libusb_name = 'libusb-1.0-64.dll'
        else:
            libusb_name = 'libusb-1.0.dll'
    elif sys.platform.startswith('linux'):
        folder_name = "linux"
        libusb_name = 'libusb-1.0.so'
    elif sys.platform.startswith('darwin'):
        folder_name = "mac"
        libusb_name = 'libusb-1.0.dylib'
    else:
        raise EnvironmentError('Could not detect OS. Only GNU/LINUX, MAC OS X and MS WIN VISTA/7/8 are supported.')
    our_dir = os.path.dirname(os.path.abspath(__file__))
    backend_path = os.path.join(our_dir, LIBRARIES_FOLDER, folder_name, 'libusb', libusb_name)
    #logger.debug('Libusb from: ' + backend_path)
    return backend_path

def get_paths_to_settings_folder():
    abs_path_to_users_home = os.path.abspath(os.path.expanduser("~"))
    folder_name = '.3dprinteros'
    if sys.platform.startswith('win'):
        abs_path_to_appdata = os.path.abspath(os.getenv('APPDATA'))
        path = os.path.join(abs_path_to_appdata, '3dprinteros')
    elif sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
        path = os.path.join(abs_path_to_users_home, folder_name)
    else:
        raise EnvironmentError('Could not detect OS. Only GNU/LINUX, MAC OS X and MS WIN VISTA/7/8 are supported.')
    local_path = os.path.dirname(os.path.abspath(__file__))
    if not os.path.exists(path):
        os.mkdir(path)
    return (path, local_path)

def current_settings_folder():
    return get_paths_to_settings_folder()[0]

def remove_pyc_files():
    for root, folder, files in os.walk(APP_FOLDER):
        for filename in files:
            if filename.endswith(".pyc"):
                os.remove(os.path.join(root, filename))

STORAGE_NAME = 'user_files'
DOWNLOAD_NAME = 'downloads'
CURRENT_SETTINGS_FOLDER = current_settings_folder()
STORAGE_FOLDER = os.path.join(CURRENT_SETTINGS_FOLDER, STORAGE_NAME)
DOWNLOAD_FOLDER = os.path.join(CURRENT_SETTINGS_FOLDER, DOWNLOAD_NAME)
UPDATE_FILE_NAME = '3dprinteros_client_update.zip'
UPDATE_FILE_PATH = os.path.join(CURRENT_SETTINGS_FOLDER, UPDATE_FILE_NAME)
CUSTOM_CACERT_PATH = os.path.join(CURRENT_SETTINGS_FOLDER, 'custom_ca.pem')
CERTIFI_CACERT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), 'certifi/cacert.pem'))

def init_folder(name, parent_folder=None):
    if not parent_folder:
        if sys.platform.startswith('win'):
            parent_folder = os.getenv('APPDATA')
            name = name.lstrip(".")
        else:
            parent_folder = os.path.expanduser("~")
    path = os.path.join(os.path.abspath(parent_folder), name)
    if os.path.isfile(path):
        os.remove(path)
    if not os.path.exists(path):
        os.mkdir(path)
    return path

CURRENT_SETTINGS_FOLDER = init_folder('.3dprinteros')
for folder in (STORAGE_NAME, DOWNLOAD_NAME):
    init_folder(folder, CURRENT_SETTINGS_FOLDER)

def remove_folder_contents(top):
    try:
        for root, dirs, files in os.walk(top, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))
    except:
        print(f'Unable to remove {top}')

def remove_downloaded_files():
    remove_folder_contents(DOWNLOAD_FOLDER)

def remove_stored_files():
    remove_folder_contents(STORAGE_FOLDER)

if __name__ == "__main__":
    remove_pyc_files()
