bl_info = {
    "name": "Folder Manager",
    "author": "Gregory Smirnoff",
    "version": (11, 0),
    "blender": (2, 80, 0),
    "location": "View3D > Add > Toolshelf",
    "description": "Manage project folders",
    "warning": "",
    "wiki_url": "",
    "category": "Project Manager",
}


import bpy
from bpy.types import Operator, AddonPreferences
from bpy.props import StringProperty, IntProperty, BoolProperty
import subprocess
import os

### Preferences

class ProjectFolderAddonPrefs(AddonPreferences):
    bl_idname = __name__
    
    project_path:StringProperty(
        name = "Main Projects Folder",
        default = "C:\\tmp\\",
        description = "Dir for project",
        subtype = 'FILE_PATH',
    )
    
    save_to_folder:BoolProperty(
        name = "Save blend to created project folder",
        default = True,
        description = "Dir for project",
    )    
    
    def draw(self, context):
        layout = self.layout
        layout.prop(self, "project_path")
        layout.prop(self, "save_to_folder")
        
    
        
### Functions

def CreateProjectFolders():
    main_folders = ("Projects", "Data", "Out")
    project_folders = ("Blender", "Krita", "Inkscape")
    data_folders = ("Archives", "Docs", "Images", "Models", "Refine", "Textures", "Video")
    out_folders = ("Images", "Preview", "Video", "Sequances")
    
    preferences = bpy.context.preferences
    addon_prefs = preferences.addons[__name__].preferences
    
    base_path = addon_prefs.project_path+"\\"+bpy.context.scene.folder_name
    
    for mf in main_folders:
        if mf == "Projects":
            for pf in project_folders:
                path = base_path+"\\"+mf+"\\"+pf
                os.makedirs(path)
                
        if mf == "Data":
            for df in data_folders:
                path = base_path+"\\"+mf+"\\"+df
                os.makedirs(path)  
                                
        if mf == "Out":
            for of in out_folders:
                path = base_path+"\\"+mf+"\\"+of
                os.makedirs(path)                               

 
def SaveToFolder():
    
    preferences = bpy.context.preferences
    addon_prefs = preferences.addons[__name__].preferences
    factor = addon_prefs.save_to_folder
    
    if factor:
        save_path = addon_prefs.project_path+"\\"+bpy.context.scene.folder_name+"\\Projects\\Blender\\"+bpy.context.scene.folder_name+"_001"+".blend"
        bpy.ops.wm.save_as_mainfile(filepath=save_path)
         
        return save_path
    else:
        return "Blend file not saved" 
    
    
def get_date():
    '''Get current date'''
    import time, datetime
    
    dataD = datetime.datetime.now()
    
    day = dataD.day
    month = dataD.month
    year = dataD.year
    
    
    
    if day < 10:
        day = '0'+str(day)
    else:
        day = str(day)
        
        
        
    if month < 10:
        month = '0'+str(month)
    else:
        month = str(month)
        
        
    year = str(year)
    
                            
    
    dataStr = day+'-'+month+'-'+year
    
    return dataStr     


def get_host_info():
    '''Get host info'''

    import platform
    
    sysInfo = platform.uname()
    
    host = sysInfo.node
    
    return host        
        
### UI


class FolderManagerMainPanel(bpy.types.Panel):
    bl_label = "Folder Manager"
    bl_idname = "FOLDER_PT_MAINPANEL"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = 'Folder Manager'

    def draw(self, context):
        layout = self.layout
        
        cool = layout.column()
        
        cool.label(text = "Create")
        
        cool.prop(context.scene, 'folder_name')
        cool.prop(context.scene, 'project_path') 
        cool.operator('create.folders')     
        
        cool.label(text = "Manage")
        
        cool.operator('project.folder_operator')
        cool.operator('data.folder_operator')
        cool.operator('out.folder_operator')
        
        
class FolderManagerFilebrowserPanel(bpy.types.Panel):
    bl_space_type = 'FILE_BROWSER'
    bl_region_type = 'TOOLS'
    #bl_region_type = 'UI'
    bl_label = "Directory Path"
    bl_category = "Attributes"
    bl_options = {'HIDE_HEADER'}

    def is_header_visible(self, context):
        for region in context.area.regions:
            if region.type == 'HEADER' and region.height <= 1:
                return False

        return True

    def draw(self, context):
        layout = self.layout
        space = context.space_data
        params = space.params
        
        cool = layout.column()
        
   
        
        cool.label(text = "Project Manager")
        
        cool.operator('project.folder_operator_fb')
        cool.operator('data.folder_operator_fb')
        cool.operator('out.folder_operator_fb')
        cool.separator()        
        cool.label(text='Create Folder')        
        cool.operator('bydate.folder_operator_fb', icon='NEWFOLDER')        
        cool.operator('byname.folder_operator_fb', icon='FILE_BLEND')        
        cool.operator('byhost.folder_operator_fb', icon='WORKSPACE')        
    
        

    #Create Project Folders
class CREATE_OT_FOLDERS(bpy.types.Operator):
    bl_label = "Create"
    bl_idname = 'create.folders'
    
    def execute(self, context):
        CreateProjectFolders()
        raport = SaveToFolder()
        self.report({'INFO'}, "Saved file: "+raport)
        return {"FINISHED"}


    #Open Blender project folder
class FOLDER_OT_PROJECT(bpy.types.Operator):
    bl_label = "Project"
    bl_idname = 'project.folder_operator'
    
    def execute(self, context):
        fpath = bpy.data.filepath
        basen = bpy.path.basename(bpy.data.filepath)
        new_fpath = fpath.replace( basen, "")
        new_fpath2 = new_fpath.replace( "\\", "/")
        path = 'start "" '+'"'+new_fpath2+'"'
        p = subprocess.check_output(path, shell = True)
        return {"FINISHED"}    
    
    
    #Open Data folder
class FOLDER_OT_DATA(bpy.types.Operator):
    bl_label = "Data"
    bl_idname = 'data.folder_operator'
    
    def execute(self, context):
        base_path = '//..\..\Data\\'
        base_path = bpy.path.abspath(base_path)
        path = 'start "" '+'"'+base_path+'"'
        p = subprocess.check_output(path, shell = True)
        return {"FINISHED"}
    

    
    #Open Output folder
class FOLDER_OT_OUTPUT(bpy.types.Operator):
    bl_label = "Output"
    bl_idname = 'out.folder_operator'
    
    def execute(self, context):
        base_path = '//..\..\Out\\'
        base_path = bpy.path.abspath(base_path)
        path = 'start "" '+'"'+base_path+'"'
        p = subprocess.check_output(path, shell = True)
        return {"FINISHED"}
    

#### FILEBROWSET PANELS ####    
    
    #Open Blender project folder
class FOLDER_OT_PROJECT_FB(bpy.types.Operator):
    bl_label = "Project"
    bl_idname = 'project.folder_operator_fb'
    
    def execute(self, context):
        fpath = bpy.data.filepath
        basen = bpy.path.basename(bpy.data.filepath)
        new_fpath = fpath.replace( basen, "")
        new_fpath2 = new_fpath.replace( "\\", "/")
        path = new_fpath2
        
        
        #path = bytes(path, "ascii")
        path = bytes(path, "utf-8")
        context.space_data.params.directory = path
        
        
        return {"FINISHED"}    
    
    
    #Open Data folder
class FOLDER_OT_DATA_FB(bpy.types.Operator):
    bl_label = "Data"
    bl_idname = 'data.folder_operator_fb'
    
    def execute(self, context):
        base_path = '//..\..\Data\\'
        base_path = bpy.path.abspath(base_path)
        path = base_path
        
        
        path = bytes(path, "utf-8")
        context.space_data.params.directory = path
        
        return {"FINISHED"}
    

    
    #Open Output folder
class FOLDER_OT_OUTPUT_FB(bpy.types.Operator):
    bl_label = "Output"
    bl_idname = 'out.folder_operator_fb'
    
    def execute(self, context):
        base_path = '//..\..\Out\\'
        base_path = bpy.path.abspath(base_path)
        path = base_path
        
        path = bytes(path, "utf-8")
        context.space_data.params.directory = path 
        
        return {"FINISHED"}
    
    
    #Create Date folder
class FOLDER_OT_BYDATE_FB(bpy.types.Operator):
    bl_label = "Folder By Date"
    bl_idname = 'bydate.folder_operator_fb'
    
    def execute(self, context):
        
        
        path = context.space_data.params.directory.decode("utf-8")+get_date()
        
        if not os.path.isdir(path):        
            os.makedirs(path)
            bpy.ops.file.refresh()
        
        return {"FINISHED"} 
    
    
class FOLDER_OT_BYNAME_FB(bpy.types.Operator):
    bl_label = "Folder By Name"
    bl_idname = 'byname.folder_operator_fb'
    
    def execute(self, context):
       
        fpath = bpy.data.filepath
        basen = bpy.path.basename(bpy.data.filepath) 
        
        path = context.space_data.params.directory.decode("utf-8")+basen.replace('.blend', '')
        
        if not os.path.isdir(path):        
            os.makedirs(path)
            bpy.ops.file.refresh()
        
        return {"FINISHED"}   
    
    
class FOLDER_OT_BYHOST_FB(bpy.types.Operator):
    bl_label = "Folder By Host"
    bl_idname = 'byhost.folder_operator_fb'
    
    def execute(self, context):
        
        path = context.space_data.params.directory.decode("utf-8")+get_host_info()
        
        if not os.path.isdir(path):        
            os.makedirs(path)
            bpy.ops.file.refresh()
        
        return {"FINISHED"}             
                 
        
        
def register():
    bpy.utils.register_class(ProjectFolderAddonPrefs)
    bpy.utils.register_class(FolderManagerMainPanel)
    bpy.utils.register_class(FolderManagerFilebrowserPanel)
    bpy.utils.register_class(CREATE_OT_FOLDERS)
    bpy.utils.register_class(FOLDER_OT_PROJECT)
    bpy.utils.register_class(FOLDER_OT_DATA)
    bpy.utils.register_class(FOLDER_OT_OUTPUT)
    bpy.utils.register_class(FOLDER_OT_PROJECT_FB)
    bpy.utils.register_class(FOLDER_OT_DATA_FB)
    bpy.utils.register_class(FOLDER_OT_OUTPUT_FB)    
    bpy.utils.register_class(FOLDER_OT_BYDATE_FB)    
    bpy.utils.register_class(FOLDER_OT_BYNAME_FB)    
    bpy.utils.register_class(FOLDER_OT_BYHOST_FB)    
    
    bpy.types.Scene.folder_name = bpy.props.StringProperty \
        (
         name = "Project name",
         default = "New Project",
         description = "Base project name",
         subtype = 'NONE'
        )    
    
#    bpy.types.Scene.project_path = bpy.props.StringProperty \
#        (
#         name = "Project path",
#         default = "C:\\tmp\\",
#         description = "Dir for project",
#         subtype = 'FILE_PATH'
#        )    


def unregister():
    bpy.utils.unregister_class(ProjectFolderAddonPrefs)
    bpy.utils.unregister_class(FolderManagerMainPanel)
    bpy.utils.unregister_class(FolderManagerFilebrowserPanel)
    bpy.utils.unregister_class(CREATE_OT_FOLDERS)
    bpy.utils.unregister_class(FOLDER_OT_PROJECT)
    bpy.utils.unregister_class(FOLDER_OT_DATA)
    bpy.utils.unregister_class(FOLDER_OT_OUTPUT)
    bpy.utils.unregister_class(FOLDER_OT_PROJECT_FB)
    bpy.utils.unregister_class(FOLDER_OT_DATA_FB)
    bpy.utils.unregister_class(FOLDER_OT_OUTPUT_FB)    
    bpy.utils.unregister_class(FOLDER_OT_BYDATE_FB)    
    bpy.utils.unregister_class(FOLDER_OT_BYNAME_FB)    
    bpy.utils.unregister_class(FOLDER_OT_BYHOST_FB)    
    
    del bpy.types.Scene.folder_name
    #del bpy.types.Scene.project_path
    
    


if __name__ == "__main__":
    register()        