# THIS FILE IS A PART OF VCStudio
# PYTHON 3

import os
import datetime
import platform
from subprocess import *

# studio
from studio import history

ostype = platform.system()

def Open(arg):  # XDG-OPEN (start the file in a default software)
    
    ############################################################################
    
    # This function is requested by people. I can't actually test it properly
    # because I don't use proprietary software. And in my opinion this function
    # should not even exists here. 
    
    # In a GNU/Linux system to open a file with a default program you use xdg-open
    # that does the job for you. When talking to people I figured out that similar
    # functions exist on different OS as well. But unfortunatly they are all
    # different. It's start in Windows and open in MacOS systems. Or so I 
    # understand. I could be wrong. 
    
    # I'm not going to make sure that all xdg-open calls are done using this
    # function. So if you trying to run VCStudio on non GNU/Linux system please
    # take it into concideration. You can search for xdg-open in all files. And
    # change those commands to oscall.Open() instead. ( Keep in mind it has to
    # be imported first )
    
    # I don't condone use of non-free software.  
    
    ############################################################################
    
    # For The Best OS Ever
    if ostype == "Linux":                     #####       ##        ##    ##        ##
        Popen(["xdg-open", arg])            ##      ##    ####      ##    ##        ##
    # For Stinky. Like very, very Stinky   ##             ##  ##    ##    ##        ##
    elif ostype == "Windows":             ##    ####      ##    ##  ##    ##        ##
        os.system("start "+arg)            ##   #  ##     ##     ## ##     ##      ##
    # For Not that Stinky but it is Stinky  ##      ##    ##      ####      ##    ##
    elif ostype == "Darwin":                  #####       ##        ##        ####
        os.system("open "+arg)



def file_open(win, path):
    
    ############################################################################
    
    # Now you maybe asking yourself "Why is there 2 functions to open files in
    # a default application?". Well it's because this is a VCStudio and it's a
    # bit more complicated then a regular file manager as you probably could tell.
    
    # One of the big differences is that you can manage versions of Blender to
    # be used in a particular project. For example you have a high priority,
    # high value project that you rather use Blender LTS for. And not update
    # blender. But on the other hand you might start a test / bleading edge
    # project. You probably want to have mulitple Blender versions installed in
    # the same time. And be able to use one version in one project and the other
    # version in the other project.
    
    # In Blender-Organizer legacy there is a setting to change the Blender version
    # by providing a link to the folder of where it's installed. I'm planning to
    # do similar system here. And so while calling Blender files I want to use
    # the Blender that's in the setting and not the system installed Blender.
    
    # Maybe I will expend this feature to all kinds of file formats. It's handy
    # to make all opening of files through this function. So I would not need
    # to edit this stuff in many places later on. 
    
    ############################################################################
    
    # Let's see if the file is inside the project or full path.
    
    if os.path.exists(win.project+"/"+path):
        path = win.project+"/"+path
    
    # Let's check if the file is a blend file. (I know I can read first line
    # and see if there a word BLENDER in it. But come on. )
    
    blendfile = False
    for bt in [".blend", ".blend1"]:
        if path.endswith(bt):
            blendfile = True
    
    # Executing the file
    
    if blendfile:
        Popen([get_current_blender(win), path])
        
        # Every blend file opening should be recorded to history. Because then
        # on multiuser, the other users should somehow know that changes were
        # done to the blendfile.
        
        history.record(win, path, "[Openned]")
        
    else:
        Open(path)

def copy_file(win, from_path, to_path, new_name=""):
    
    ############################################################################
    
    # This function exists because coping files is not as simple as reading one
    # and writting it to another. Blend-Files for example could have terrible
    # amount of linked stuff. And I can't be sure that the user will be always
    # using full path mode for these. And even. It's not good to do it anyway. 
    # because you want to copy the project from one folder to another and keep
    # everything pretty much intact.
    
    # So this will make sure that stuff like blend file (maybe if future other
    # files) will be copied preserving all the linking inside.
    
    ############################################################################
    
    # Let's see if the file is inside the project or full path.
    
    if os.path.exists(win.project+"/"+from_path):
        from_path = win.project+"/"+from_path
    if os.path.exists(win.project+"/"+to_path):
        to_path = win.project+"/"+to_path
    
    # Now let's make sure that unless specified we are not overwritting some
    # existing file. 
    
    if not new_name:
        
        new_name = from_path[from_path.rfind("/")+1:]
        count = 0
        while new_name in os.listdir(to_path):
            count = count + 1
            new_name = from_path[from_path.rfind("/")+1:from_path.rfind(".")]+"_"+str(count)+from_path[from_path.rfind("."):]
    
    # Now let's combine name and name
    to_path = to_path + "/" + new_name
    
    still = True
    
    # Let's check that we got a blend file
    blendfile = False
    for bt in [".blend", ".blend1"]:
        if from_path.endswith(bt):
            blendfile = True
    
    if blendfile:
        # Now before we copy blend file we need to check whether Blender is even 
        # installed.
        
        noblender = os.system(get_current_blender(win)+" -v") # It's a simple version check.
        
        # If there is no Blender installed os.system will return a value higher then 0.
        
        if not noblender:
            still = False
            
            # Now what we are going to do is start blender using a little expression
            # to force it to save file as.
            
            os.system(get_current_blender(win)\
            +" -b "\
            +from_path.replace(" ", "\ ")\
            +" --python-expr import\ bpy\;\ bpy.ops.wm.save_as_mainfile\(filepath=\\\""\
            +to_path.replace(" ", "\ ")+"\\\"\)") 
        
        # Writting to history. Since each copy of a file is adding a blendfile.
        history.record(win, to_path, "[Added]")
        
    if still:
        
        # If it's not a blendfile we going to use this.
        with open(from_path, "rb") as in_file, open(to_path, "wb") as out_file:
            out_file.write(in_file.read())
            
    return to_path                
    
def get_current_blender(win):
    
    ############################################################################
    
    # This function is going to get the current blender version from the settings
    # (At the moment the feature is not implemented. So this is a placeholder.)
    
    ############################################################################
    
    return "blender"