/*-------------------------------------------------------------------------------
Copyright (c)2000 TogetherSoft Corporation. Patents pending. All rights reserved.
-------------------------------------------------------------------------------*/

package com.togethersoft.modules.patterns.UNIVERSAL.MEMBER.Stub_Implementation;

import com.togethersoft.openapi.sci.*;
import com.togethersoft.openapi.sci.enum.*;

import com.togethersoft.openapi.sci.pattern.SciPattern;
import com.togethersoft.openapi.sci.pattern.SciPatternProperty;

import com.togethersoft.openapi.ide.message.IdeMessageManagerAccess;
import com.togethersoft.openapi.ide.message.IdeMessageType;

import com.togethersoft.modules.patterns.UNIVERSAL.PatternBase;
import com.togethersoft.modules.patterns.UNIVERSAL.PatternBaseException;

/**
 * Stub Implementation pattern for members
 * @author TogetherSoft
 */
public class Pattern extends PatternBase implements SciPattern {

    public boolean prepare() {
        SciMember member = (SciMember) getPropertyValue(SciPatternProperty.ELEMENT);
        if (!(member instanceof SciOperation)) {
            return false;
        }
        if (!member.canSetProperty(SciProperty.ABSTRACT, false)) {
            return false;
        }
        return true;
    }

    public boolean canApply() {
        return true;
    }

    public void apply() {
        if (!canApply()) {
            return;
        }
        super.apply();

        SciOperation operation = (SciOperation) getPropertyValue(SciPatternProperty.ELEMENT);
        operation.setProperty(SciProperty.ABSTRACT, false);

        setPropertyValue(SciPatternProperty.RESULT_ELEMENT, operation);

        SciType sciType = operation.getReturnType();
        if (sciType == null) {
            return;
        }

        if (!EMPTY_STRING.equals(operation.getBody().getText().trim())) {
            // operation already has some body
            return;
        }

        // set operation body
        String typeText = sciType.getText();
        String code = "\n// Write your code here\n";

        if (VOID.equals(typeText)) {
            // operation body is empty
        }
        else if (getLanguageSpecificBooleanStatement().equals(typeText)) {
            code += "return false;";
        }
        else if (INT.equals(typeText) || LONG.equals(typeText) ||
                 CHAR.equals(typeText) || DOUBLE.equals(typeText) ||
                 FLOAT.equals(typeText) || SHORT.equals(typeText) ||
                 BYTE.equals(typeText)) {
            code += "return 0;";
        }
        else {
            code += "return " + getLanguageSpecificNullStatement() + ";";
        }

        try {
            operation.setBody(getGenericFactory().newCodeBlock(code));
        }
        catch(SciGenericFactoryException e) {
            IdeMessageManagerAccess.printMessage(IdeMessageType.ERROR, CODE_GENERATION_ERROR);
        }
    }
}
