/*
 * Copyright 2017 Jeffrey Bonevich
 *
 * 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 com.bonevich.ecslocal.infrastructure.persistence.filesys.taskdef;

import com.amazonaws.services.ecs.model.TaskDefinition;
import com.bonevich.ecslocal.domain.model.EcsArn;
import com.bonevich.ecslocal.domain.model.EcsLocalException;
import com.bonevich.ecslocal.domain.model.taskdef.TaskDefinitionRepository;
import com.bonevich.ecslocal.infrastructure.persistence.filesys.EcsDatabase;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class TaskDefinitionRepositoryImpl implements TaskDefinitionRepository {

    private final EcsDatabase database;
    private final Map<String, TaskDefinition> definitionsByFamily;

    public TaskDefinitionRepositoryImpl(EcsDatabase database) {
        this.database = database;
        this.definitionsByFamily = database.getTaskDefinitions().stream().collect(Collectors.toMap(TaskDefinition::getFamily, Function.identity()));
    }

    @Override
    public TaskDefinition getTaskDefinition(String taskDefinition) {
        String name = taskDefinition;
        String[] split = taskDefinition.split(":");
        if (split.length > 1) {
            name = split[split.length - 2];
        }
        if (split.length > 2) {
            String taskDefAndName = split[split.length - 2];
            name = taskDefAndName.substring(taskDefAndName.indexOf("/") + 1);
        }
        TaskDefinition definition = definitionsByFamily.get(name);
        if (definition == null) {
            throw EcsLocalException.clientException("TaskDefinition not found: " + taskDefinition);
        }
        return definition;
    }

    @Override
    public TaskDefinition save(TaskDefinition taskDefinition) {
        taskDefinition.withTaskDefinitionArn(EcsArn.taskDefinitionArn(taskDefinition.getFamily()));
        return addTaskDefinition(taskDefinition);
    }

    private TaskDefinition addTaskDefinition(TaskDefinition taskDefinition) {
        definitionsByFamily.put(taskDefinition.getFamily(), taskDefinition);
        database.addTaskDefinition(taskDefinition);
        return taskDefinition;
    }

}
