/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you 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
 *
 *    https://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 grails.gorm.tests.proxy

import grails.gorm.tests.entities.Club
import grails.gorm.tests.entities.Team
import org.apache.grails.data.hibernate5.core.GrailsDataHibernate5TckManager
import org.apache.grails.data.testing.tck.base.GrailsDataTckSpec
import org.grails.orm.hibernate.proxy.HibernateProxyHandler
import spock.lang.Shared

/**
 * Contains misc proxy tests using Hibernate defaults, which is ByteBuddy.
 * These should all be passing for Gorm to be operating correctly with Groovy.
 */
class ByteBuddyProxySpec extends GrailsDataTckSpec<GrailsDataHibernate5TckManager> {
    void setupSpec() {
        manager.registerDomainClasses(Team, Club)
    }

    @Shared
    HibernateProxyHandler proxyHandler = new HibernateProxyHandler()

    Team createATeam(){
        Club c = new Club(name: "DOOM Club").save(failOnError:true)
        Team team = new Team(name: "The A-Team", club: c).save(failOnError:true, flush:true)
        return team
    }

    void "getId and id property checks dont initialize proxy if in a CompileStatic method"() {
        when:
        Team team = createATeam()
        manager.session.clear()
        team = Team.load(team.id)

        then:"The asserts on getId and id should not initialize proxy when statically compiled"
        StaticTestUtil.team_id_asserts(team)
        !proxyHandler.isInitialized(team)

        StaticTestUtil.club_id_asserts(team)
        !proxyHandler.isInitialized(team.club)
    }

    void "getId and id dont initialize proxy"() {
        when:"load proxy"
        Team team = createATeam()
        manager.session.clear()
        team = Team.load(team.id)

        then:"The asserts on getId and id should not initialize proxy"
        proxyHandler.isProxy(team)
        team.getId()
        !proxyHandler.isInitialized(team)

        team.id
        !proxyHandler.isInitialized(team)

        and: "the getAt check for id should not initialize"
        team['id']
        !proxyHandler.isInitialized(team)
    }

    void "id access on a detached proxy does not initialize it or require a session"() {
        when: "a proxy is detached from its session"
        Team team = createATeam()
        def id = team.id
        manager.session.clear()
        team = Team.load(id)
        manager.session.clear()

        then: "id access works without a session and does not initialize the proxy"
        team.id == id
        team.getId() == id
        team.ident() == id
        !proxyHandler.isInitialized(team)
        proxyHandler.getIdentifier(team) == id
    }

    void "unwrap of a detached uninitialized proxy requires a session but identifier access does not"() {
        given: "a proxy detached from its session"
        Team team = createATeam()
        def id = team.id
        manager.session.clear()
        team = Team.load(id)
        manager.session.clear()

        expect: "the identifier is available without a session"
        proxyHandler.getIdentifier(team) == id
        team.ident() == id
        !proxyHandler.isInitialized(team)

        when: "the proxy is unwrapped, which must materialize the real entity"
        proxyHandler.unwrap(team)

        then: "a database hit is unavoidable, so without a session this fails - code that only \
needs the identifier must use id/ident()/getIdentifier() instead of unwrapping"
        thrown(org.hibernate.LazyInitializationException)
    }

    void "truthy check on instance should not initialize proxy"() {
        when:"load proxy"
        Team team = createATeam()
        manager.session.clear()
        team = Team.load(team.id)

        then:"The asserts on the intance should not init proxy"
        team
        !proxyHandler.isInitialized(team)

        and: "truthy check on association should not initialize"
        team.club
        !proxyHandler.isInitialized(team.club)
    }

    void "id checks on association should not initialize its proxy"() {
        when:"load instance"
        Team team = createATeam()
        manager.session.clear()
        team = Team.load(team.id)

        then:"The asserts on the intance should not init proxy"
        !proxyHandler.isInitialized(team.club)

        team.club.getId()
        !proxyHandler.isInitialized(team.club)

        team.club.id
        !proxyHandler.isInitialized(team.club)

        team.clubId
        !proxyHandler.isInitialized(team.club)

        and: "the getAt check for id should not initialize"
        team.club['id']
        !proxyHandler.isInitialized(team.club)
    }

    void "toString initializes the proxy and delegates to the entity implementation by default"() {
        when:"load proxy"
        Team team = createATeam()
        def clubId = team.club.id
        manager.session.clear()
        Club club = Club.load(clubId)

        then:"the proxy starts uninitialized"
        proxyHandler.isProxy(club)
        !proxyHandler.isInitialized(club)

        when:"toString is called"
        String value = club.toString()

        then:"the entity's own toString runs, which requires initialization"
        value == "DOOM Club"
        proxyHandler.isInitialized(club)
    }

    void "isDirty should not intialize the association proxy"() {
        when:"load instance"
        Team team = createATeam()
        manager.session.clear()
        team = Team.load(team.id)

        then:"The asserts on the intance should not init proxy"
        !proxyHandler.isInitialized(team)

        // a clean isDirty() check is answered by the Groovy-aware interceptor without initializing
        !team.isDirty()
        !proxyHandler.isInitialized(team)
        //it should not have initialized the association
        !proxyHandler.isInitialized(team.club)

        when: "its made dirty"
        team.name = "B-Team"

        then:
        team.isDirty()
        //still should not have initialized it.
        !proxyHandler.isInitialized(team.club)
    }

}
