/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.spockframework.idea

import com.intellij.psi.PsiVariable

// only tested with 11.1, so play it safe and bail out on earlier version
if (!supportsVersion("11.1")) return

def ctx = context(ctype: "spock.lang.Specification", scope: closureScope(isArg: true))

// with(foo) { /* delegates to foo */ }
// with(foo, Bar) { /* delegates to instance of Bar */ }
contributor(ctx, {
  def call = enclosingCall("with")
  if (call) {
    def method = call.bind()
    def clazz = method?.containingClass
    if (clazz?.qualName == "spock.lang.Specification") {
      def args = call.arguments
      if (args?.size() == 1) {
        delegatesTo(args[0])
      } else if (args?.size() == 2) {
        def type = args[1].type
        if (type?.className == "Class") {
          delegatesTo(type.parameters[0].resolve())
        }
      }
    }
  }
})

// Mock(Foo) { /* delegates to instance of type Foo */ }
// Foo x = Mock { /* delegates to instance of type Foo */ }
contributor(ctx, {
  def call = enclosingCall("Mock") ?: enclosingCall("Stub") ?: enclosingCall("Spy") ?:
    enclosingCall("GroovyMock") ?: enclosingCall("GroovyStub") ?: enclosingCall("GroovySpy")
  if (call) {
    def method = call.bind()
    def clazz = method?.containingClass
    if (clazz?.qualName == "spock.lang.MockingApi") {
      def mockType = call.arguments.find { it.type.className == "Class" }
      if (mockType) {
        def typeParameter = mockType.type.parameters[0]
        delegatesTo(typeParameter.resolve())
        return
      }
      def callContext = call.context
      if (callContext instanceof PsiVariable) {
        delegatesTo(callContext.typeGroovy.resolve())
      }
    }
  }
})


