import logging
import zlib
import uuid

from orangescape.model.engine.execution.ProcessEngine import ProcessNode
from orangescape.model.server.services.AppService import AppSetupService, copyChange

from orangescape.model.engine.exception.Error import ServerError
from orangescape.model.engine.exception.ErrorMessage import Server2001
import appconfig as config

class AppSetupProcessNode(ProcessNode):

    def enter(self):
        logging.debug('Creating application system models')
        self.sheet.getDataObject().ApplicationId = self.sheet.getSheetId()
        templateId = self.sheet.getValue('AppTemplate')
        if templateId:
            from orangescape.model.server.util.privateserializer import SheetSerializer
            templateApp = self.session.get(templateId, self.sheet.getSheetMetadata())
            self.component.update(self.sheet, {'MetadataVersion':templateApp.getValue('MetadataVersion')})
            data = SheetSerializer(self.session, templateApp, {'Sheet008' : ['CellMetadata_99dcc7f8_f829_4da1_8d4f_a00c57684e45','Cell_001_002_006', 'Cell_029_002_006', 'Cell_015_002_006', 'Ced2a6420a28ae43539a38ced226abc6de', 'CellMetadata_c9e14075_5719_42b0_b62a_217477894f41', 'Cell_016_002_006', 'Cell_027_002_006']}, True).serializeApplication()
            service = AppSetupService(self.component)
            service.insertAppRecords(self.sheet, data)
            service.copySheet_n_Attachments(self.sheet, templateApp)
        else:
            self.component.update(self.sheet, {'MetadataVersion':config.metadataVersion})
            from orangescape.tests.functional.dev.primary.Ap_2 import Ap_2 as d
            data = copyChange(d)
            service = AppSetupService(self.component)
            service.insertAppRecords(self.sheet, data)
            service.createSheet_n_Attachments(self.sheet)