/*
 * Copyright 2016-2018 shardingsphere.io.
 * <p>
 * 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.
 * </p>
 */

package io.shardingsphere.orchestration.internal.registry.config.listener;

import com.google.common.base.Strings;
import io.shardingsphere.api.config.rule.RuleConfiguration;
import io.shardingsphere.orchestration.internal.registry.config.event.ConfigMapChangedEvent;
import io.shardingsphere.orchestration.internal.registry.config.event.DataSourceChangedEvent;
import io.shardingsphere.orchestration.internal.registry.config.event.IgnoredChangedEvent;
import io.shardingsphere.orchestration.internal.registry.config.event.MasterSlaveRuleChangedEvent;
import io.shardingsphere.orchestration.internal.registry.config.event.SchemaChangedEvent;
import io.shardingsphere.orchestration.internal.registry.config.event.ShardingRuleChangedEvent;
import io.shardingsphere.orchestration.internal.registry.config.node.ConfigurationNode;
import io.shardingsphere.orchestration.internal.registry.config.service.ConfigurationService;
import io.shardingsphere.orchestration.internal.registry.listener.PostShardingOrchestrationEventListener;
import io.shardingsphere.orchestration.internal.registry.listener.ShardingOrchestrationEvent;
import io.shardingsphere.orchestration.reg.api.RegistryCenter;
import io.shardingsphere.orchestration.reg.listener.DataChangedEvent;
import io.shardingsphere.orchestration.reg.listener.DataChangedEvent.ChangedType;
import io.shardingsphere.orchestration.yaml.ConfigurationYamlConverter;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;

/**
 * Schema changed listener.
 *
 * @author panjuan
 */
public final class SchemaChangedListener extends PostShardingOrchestrationEventListener {
    
    private final ConfigurationService configurationService;
    
    private final ConfigurationNode configurationNode;
    
    private final Collection<String> existedSchemas = new LinkedList<>();
    
    public SchemaChangedListener(final String name, final RegistryCenter regCenter, final ConfigurationService configurationService) {
        super(regCenter, new ConfigurationNode(name).getSchemaPath());
        this.configurationService = configurationService;
        configurationNode = new ConfigurationNode(name);
    }
    
    @Override
    protected ShardingOrchestrationEvent createShardingOrchestrationEvent(final DataChangedEvent event) {
        String schemaName = configurationNode.getSchemaName(event.getKey());
        if (Strings.isNullOrEmpty(schemaName)) {
            return new IgnoredChangedEvent();
        }
        if (ChangedType.UPDATED == event.getChangedType()) {
            if (existedSchemas.contains(schemaName)) {
                if (event.getKey().equals(configurationNode.getDataSourcePath(schemaName))) {
                    return createDataSourceChangedEvent(schemaName, event);
                } else {
                    return createRuleChangedEvent(schemaName, event);
                }
            } else {
                if (isSufficientToInitialize(schemaName)) {
                    
                }
            }
        }
        
        
        System.out.println(event.getKey());
        System.out.println(event.getValue());
        if (ChangedType.DELETED == event.getChangedType()) {
            event.getKey();
        }
        return new ConfigMapChangedEvent(Collections.EMPTY_MAP);
    }
    
    private DataSourceChangedEvent createDataSourceChangedEvent(final String schemaName, final DataChangedEvent event) {
        return new DataSourceChangedEvent(schemaName, ConfigurationYamlConverter.loadDataSourceConfigurations(event.getValue()));
    }
    
    private ShardingOrchestrationEvent createRuleChangedEvent(final String schemaName, final DataChangedEvent event) {
        return isShardingRule(event) ? getShardingRuleChangedEvent(schemaName, event.getValue()) : getMasterSlaveRuleChangedEvent(schemaName, event.getValue());
    }
    
    private boolean isShardingRule(final DataChangedEvent event) {
        return event.getValue().contains("tables:\n");
    }
    
    private ShardingRuleChangedEvent getShardingRuleChangedEvent(final String schemaName, final String ruleValue) {
        return new ShardingRuleChangedEvent(schemaName, ConfigurationYamlConverter.loadShardingRuleConfiguration(ruleValue));
    }
    
    private MasterSlaveRuleChangedEvent getMasterSlaveRuleChangedEvent(final String schemaName, final String ruleValue) {
        return new MasterSlaveRuleChangedEvent(schemaName, ConfigurationYamlConverter.loadMasterSlaveRuleConfiguration(ruleValue));
    }
    
    private boolean isSufficientToInitialize(final String schemaName) {
        return configurationService.hasDataSourceConfiguration(schemaName) && configurationService.hasRuleConfiguration(schemaName);
    }
    
    private SchemaChangedEvent createSchemaChangedEvent(final String schemaName) {
        return new SchemaChangedEvent(schemaName, configurationService.loadDataSourceConfigurations(schemaName), createRuleConfiguration(schemaName));
    }
    
    private RuleConfiguration createRuleConfiguration(final String schemaName) {
        return configurationService.isShardingRule(schemaName) ? configurationService.loadShardingRuleConfiguration(schemaName) : configurationService.loadMasterSlaveRuleConfiguration(schemaName);
    }
}

@@ -792,101 +792,8 @@
 on;%0A
-import io.shardingsphere.orchestration.internal.registry.config.event.ConfigMapChangedEvent;%0A
 impo
@@ -1144,24 +1144,123 @@
 event.Schema
+AddChangedEvent;%0Aimport io.shardingsphere.orchestration.internal.registry.config.event.SchemaDelete
 ChangedEvent
@@ -2060,38 +2060,8 @@
 on;%0A
-import java.util.Collections;%0A
 impo
@@ -2527,16 +2527,62 @@
 gCenter,
+ final Collection%3CString%3E shardingSchemaNames,
  final C
@@ -2807,24 +2807,76 @@
 Node(name);%0A
+        existedSchemas.addAll(shardingSchemaNames);%0A
     %7D%0A    %0A 
@@ -3475,36 +3475,25 @@
            %7D
- else %7B%0A    
+%0A
             
@@ -3546,34 +3546,16 @@
 event);%0A
-                %7D%0A
         
@@ -3639,32 +3639,63 @@
                 
+existedSchemas.add(schemaName);
 %0A               
@@ -3699,23 +3699,56 @@
     
-%7D%0A
     
-        %7D
+return createSchemaChangedEvent(schemaName);
 %0A   
@@ -3752,26 +3752,24 @@
         
-%7D%0A
         
 %0A       
@@ -3752,32 +3752,33 @@
                 
+%7D
 %0A        %0A      
@@ -3770,25 +3770,24 @@
         
-%0A
         
 System.o
@@ -3782,42 +3782,40 @@
     
-System.out.println(event.getKey
+return new IgnoredChangedEvent
 ()
-)
 ;%0A  
@@ -3824,45 +3824,23 @@
     
-System.out.println(event.getValue());
+    %7D%0A        %7D
 %0A   
@@ -3910,28 +3910,108 @@
        e
-vent.getKey(
+xistedSchemas.remove(schemaName);%0A            return new SchemaDeleteChangedEvent(schemaName
 );%0A     
@@ -4038,17 +4038,15 @@
 new 
-ConfigMap
+Ignored
 Chan
@@ -4058,29 +4058,8 @@
 ent(
-Collections.EMPTY_MAP
 );%0A 
@@ -5502,24 +5502,27 @@
 ivate Schema
+Add
 ChangedEvent
@@ -5595,24 +5595,27 @@
 n new Schema
+Add
 ChangedEvent

use existedSchemas