'''
Created on 19 lut 2020

@author: fpawlak
'''

from __future__ import print_function
import sys
import errno
import os
from Classes.CodesysLibsScriptsException import CodesysLibsScriptsException
from Classes.LibraryRestrictions import LibraryRestrictions

class ProjectCompiller():
    def __init__(self, projects, projectPath=None):
        self.projects = projects
        
        if projectPath is not None:
            self.project = self.openProject(projectPath)
        else:
            self.project = self.loadCurrentProject()
            self.project.save()
            
    
    
    def openProject(self, projectPath):  
        print('Opening project: {}'.format(projectPath), end='')
        sys.stdout.flush()
        
        try:
            project = self.projects.open(projectPath)
            print(' -> SUCCESS')
            return project
        except Exception as e:
            print(' -> ERROR')
            raise OpenProjectException(e)
        
    
    def loadCurrentProject(self):
        print('No path to project', end='')
        sys.stdout.flush()
         
        if self.projects.primary != None:
            print(' -> Using current project')
            return self.projects.primary
        else:
            print(' and no opened project -> ERROR')
            raise NoMainProjectException(None)
        
    
    def compile(self, config, path, asTestLib=True):
        libraryRestrictions = LibraryRestrictions(config.main.company, not asTestLib)
        projectInfo = self.project.get_project_info()
        
        try:
            libraryRestrictions.checkName(projectInfo)
            libraryRestrictions.checkDeveloper(projectInfo)
            libraryRestrictions.checkIsReleased(projectInfo)

            print('Compiling project', end='')
            sys.stdout.flush()
            
            if asTestLib:
                projectInfo.title = "__DEVELOP__ - " + projectInfo.title
                
            try:
                os.makedirs('{}\\{}\\{}'.format(path, projectInfo.title, projectInfo.version), 0755)
            except OSError as e:
                if not (e.errno == errno.EEXIST and os.path.isdir('{}\\{}\\{}'.format(path, projectInfo.title, projectInfo.version))):
                    raise
            self.project.save_as_compiled_library('{}\\{}\\{}\\{}-{}.compiled-library'.format(path, projectInfo.title, projectInfo.version, projectInfo.title, projectInfo.version))
            print(' ->SUCCESS')
            print('Library saved at: {}\\{}\\{}\\{}-{}.compiled-library'.format(path, projectInfo.title, projectInfo.version, projectInfo.title, projectInfo.version))

            return LibraryInfo(projectInfo.company, projectInfo.title, projectInfo.version, '{}\\{}\\{}-{}.compiled-library'.format(projectInfo.title, projectInfo.version, projectInfo.title, projectInfo.version))
            
        except Exception as e:
            print(' -> ERROR')
            raise ProjectCompileException(e)
        finally:
            if projectInfo.title.startswith("__DEVELOP__ - "):
                projectInfo.title = projectInfo.title[14:]
            
            
            
class LibraryInfo:
    def __init__(self, company, name, version, path):
        self.company = company
        self.name = name
        self.version = version
        self.path = path
    
    def getFullName(self):
        return '{}, {} ({})'.format(self.name, self.version, self.company)
        

        
class NoMainProjectException(CodesysLibsScriptsException):
    pass

class OpenProjectException(CodesysLibsScriptsException):
    pass

class ProjectCompileException(CodesysLibsScriptsException):
    pass