/*
 * 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.shardingsphere.scaling.core.api.impl;

import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;
import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepositoryConfiguration;
import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent;
import org.apache.shardingsphere.scaling.core.api.GovernanceRepositoryAPI;
import org.apache.shardingsphere.scaling.core.api.ScalingAPIFactory;
import org.apache.shardingsphere.scaling.core.common.constant.ScalingConstant;
import org.apache.shardingsphere.scaling.core.config.DumperConfiguration;
import org.apache.shardingsphere.scaling.core.config.InventoryDumperConfiguration;
import org.apache.shardingsphere.scaling.core.config.ScalingContext;
import org.apache.shardingsphere.scaling.core.config.ServerConfiguration;
import org.apache.shardingsphere.scaling.core.config.TaskConfiguration;
import org.apache.shardingsphere.scaling.core.fixture.EmbedTestingServer;
import org.apache.shardingsphere.scaling.core.job.JobContext;
import org.apache.shardingsphere.scaling.core.job.position.PlaceholderPosition;
import org.apache.shardingsphere.scaling.core.job.progress.JobProgress;
import org.apache.shardingsphere.scaling.core.job.task.ScalingTaskFactory;
import org.apache.shardingsphere.scaling.core.job.task.incremental.IncrementalTask;
import org.apache.shardingsphere.scaling.core.job.task.inventory.InventoryTask;
import org.apache.shardingsphere.scaling.core.util.ReflectionUtil;
import org.apache.shardingsphere.scaling.core.util.ResourceUtil;
import org.junit.BeforeClass;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;

public final class GovernanceRepositoryAPIImplTest {
    
    private static GovernanceRepositoryAPI governanceRepositoryAPI;
    
    @BeforeClass
    public static void beforeClass() throws Exception {
        EmbedTestingServer.start();
        ReflectionUtil.setFieldValue(ScalingContext.getInstance(), "serverConfig", mockServerConfig());
        governanceRepositoryAPI = ScalingAPIFactory.getGovernanceRepositoryAPI();
    }
    
    @Test
    public void assertPersistJobProgress() {
        JobContext jobContext = mockJobContext();
        governanceRepositoryAPI.persistJobProgress(jobContext);
        JobProgress actual = governanceRepositoryAPI.getJobProgress(jobContext.getJobId(), jobContext.getShardingItem());
        assertThat(actual.toString(), is(ResourceUtil.readFileAndIgnoreComments("governance-repository.yaml")));
    }
    
    @Test
    public void assertDeleteJob() {
        governanceRepositoryAPI.persist(ScalingConstant.SCALING_ROOT + "/1", "");
        governanceRepositoryAPI.deleteJob(1L);
        JobProgress actual = governanceRepositoryAPI.getJobProgress(0L, 0);
        assertNull(actual);
    }
    
    @Test
    public void assertGetChildrenKeys() {
        governanceRepositoryAPI.persist(ScalingConstant.SCALING_ROOT + "/1", "");
        List<String> actual = governanceRepositoryAPI.getChildrenKeys(ScalingConstant.SCALING_ROOT);
        assertFalse(actual.isEmpty());
    }
    
    @Test
    public void assertWatch() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        String key = ScalingConstant.SCALING_ROOT + "/1";
        governanceRepositoryAPI.watch(ScalingConstant.SCALING_ROOT, event -> {
            if (event.getKey().equals(key)) {
                assertThat(event.getType(), is(DataChangedEvent.Type.ADDED));
                countDownLatch.countDown();
            }
        });
        governanceRepositoryAPI.persist(key, "");
        countDownLatch.await();
    }
    
    private static ServerConfiguration mockServerConfig() {
        ServerConfiguration result = new ServerConfiguration();
        result.setModeConfiguration(new ModeConfiguration("Cluster", new ClusterPersistRepositoryConfiguration("Zookeeper", "test", EmbedTestingServer.getConnectionString(), null), true));
        return result;
    }
    
    private JobContext mockJobContext() {
        JobContext result = new JobContext(ResourceUtil.mockJobConfig());
        TaskConfiguration taskConfig = result.getTaskConfigs().iterator().next();
        result.getInventoryTasks().add(mockInventoryTask(taskConfig));
        result.getIncrementalTasks().add(mockIncrementalTask(taskConfig));
        return result;
    }
    
    private InventoryTask mockInventoryTask(final TaskConfiguration taskConfig) {
        InventoryDumperConfiguration dumperConfig = new InventoryDumperConfiguration(taskConfig.getDumperConfig());
        dumperConfig.setPosition(new PlaceholderPosition());
        dumperConfig.setTableName("t_order");
        dumperConfig.setPrimaryKey("order_id");
        dumperConfig.setShardingItem(0);
        return ScalingTaskFactory.createInventoryTask(dumperConfig, taskConfig.getImporterConfig());
    }
    
    private IncrementalTask mockIncrementalTask(final TaskConfiguration taskConfig) {
        DumperConfiguration dumperConfig = taskConfig.getDumperConfig();
        dumperConfig.setPosition(new PlaceholderPosition());
        return ScalingTaskFactory.createIncrementalTask(3, dumperConfig, taskConfig.getImporterConfig());
    }
}

@@ -1100,24 +1100,113 @@
 angedEvent;%0A
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent.Type;%0A
 import org.a
@@ -2568,16 +2568,153 @@
 nLatch;%0A
+import java.util.concurrent.TimeUnit;%0Aimport java.util.concurrent.atomic.AtomicReference;%0A%0Aimport static org.hamcrest.CoreMatchers.anyOf;
 %0Aimport 
@@ -2794,16 +2794,62 @@
 tFalse;%0A
+import static org.junit.Assert.assertNotNull;%0A
 import s
@@ -2925,16 +2925,59 @@
 ertThat;
+%0Aimport static org.junit.Assert.assertTrue;
 %0A%0Apublic
@@ -4459,32 +4459,116 @@
 ptedException %7B%0A
+        AtomicReference%3CDataChangedEvent%3E eventReference = new AtomicReference%3C%3E();%0A
         CountDow
@@ -4817,67 +4817,32 @@
     
-assertThat(event.getType(), is(DataChangedEvent.Type.ADDED)
+eventReference.set(event
 );%0A 
@@ -4972,29 +4972,267 @@
     
-countDownLatch.await(
+boolean awaitResult = countDownLatch.await(10, TimeUnit.SECONDS);%0A        assertTrue(awaitResult);%0A        DataChangedEvent event = eventReference.get();%0A        assertNotNull(event);%0A        assertThat(event.getType(), anyOf(is(Type.ADDED), is(Type.UPDATED))
 );%0A 

Improve assertWatch (#12478)