'''
Created on 19 lut 2020

@author: fpawlak
'''

from __future__ import print_function
from Classes.ProjectCompiller import ProjectCompiller
from Classes.CodesysLibsScriptsException import CodesysLibsScriptsException
from Classes.Config import Config
from Classes.TemporaryFiles import TempDir
from Classes.LibrariesInstaller import LibrariesInstaller
import sys
import os
import traceback

class ProjectSaveAsDevelopLibraryException(CodesysLibsScriptsException):
    pass
    
    
config = Config(os.path.dirname(__file__) + '\\config.cfg');
tempDir = TempDir()
print(tempDir)

try:
    installer = LibrariesInstaller(librarymanager)
    repository = installer.getRepository(config.developRepository)
            
    if projects.primary != None:
        print('Using current project', end='')
        sys.stdout.flush()
        
        project = projects.primary
        print(' -> "{}"'.format(project.path))
        
        projectInfo = project.get_project_info()
        
        try:
            print('Saving current project as DEVELOP library', end='')
            sys.stdout.flush()
            projectInfo.title = "__DEVELOP__ - " + projectInfo.title
            project.save()

            
            installer.installLib(repository, project.path)
            print(' -> SUCCESS')
            
        except Exception as e:
            print(' -> ERROR')
            raise ProjectSaveAsDevelopLibraryException(e)
        finally:
            if projectInfo.title.startswith("__DEVELOP__ - "):
                projectInfo.title = projectInfo.title[14:]
                project.save()
                
    else:
        print(' and no opened project -> ERROR')
        raise NoMainProjectException(None)
    
    
        
except CodesysLibsScriptsException as e:
    print(e.mainException)
    traceback.print_exc()
    sys.exit(-1)