/*
 * 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
 *
 *     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.apache.kylin.common.persistence.transaction;

import java.util.concurrent.TimeUnit;

import org.assertj.core.util.Lists;
import org.awaitility.Awaitility;
import org.junit.Assert;
import org.junit.jupiter.api.Test;

import com.google.common.collect.Maps;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.val;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TransactionLockTest {

    @Test
    public void testStravition() {
        val threads = Lists.<LogicThread> newArrayList();

        for (int i = 0; i < 10; i++) {
            val t = new LogicThread(i % 4 != 0);
            t.start();
            threads.add(t);
        }

        Awaitility.await().atMost(2, TimeUnit.MINUTES)
                .until(() -> threads.stream().map(t -> t.getCount() > 10).reduce(true, (l, r) -> l && r));

        long maxCount = threads.stream().mapToLong(LogicThread::getCount).max().getAsLong();
        long minCount = threads.stream().mapToLong(LogicThread::getCount).min().getAsLong();
        Assert.assertTrue(maxCount - minCount <= 1);

        TransactionLock.projectLocks = Maps.newConcurrentMap();
        for (LogicThread thread : threads) {
            thread.interrupt();
        }

    }

    @RequiredArgsConstructor
    static class LogicThread extends Thread {

        final boolean isReader;

        @Getter
        long count = 0;

        @Override
        public void run() {
            super.run();
            val tLock = TransactionLock.getLock("p0", isReader);
            while (count < 20) {
                tLock.lock();
                log.debug("lock by {} {}, {}", isReader ? "reader" : "writer", Thread.currentThread().getName(), count);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    tLock.unlock();
                    count++;
                }
            }
        }
    }

}
