package com.armstrongconsulting.acprotasks;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.armstrongconsulting.acprotasks.client.AcproConnector;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.tasks.Task;
import com.intellij.tasks.TaskRepositoryType;
import com.intellij.tasks.impl.BaseRepository;
import com.intellij.util.xmlb.annotations.Tag;

import feign.FeignException;

@Tag(AcproRepositoryType.NAME)
public class AcproRepository extends BaseRepository
{
    private final Logger logger = LoggerFactory.getLogger(AcproRepository.class);

    private String apiKey = null;

    public AcproRepository(TaskRepositoryType type)
    {
        super(type);
    }

    public AcproRepository(AcproRepository other)
    {
        super(other);
        this.apiKey = other.apiKey;
    }

    public AcproRepository()
    {
    }

    @Override
    public @Nullable Task findTask(@NotNull String id) throws Exception
    {
        return null;
    }

    @Override
    public @NotNull BaseRepository clone()
    {
        return new AcproRepository(this);
    }

    @Override
    public Task[] getIssues(@Nullable String query, int offset, int limit, boolean withClosed,
        @NotNull ProgressIndicator cancelled) throws Exception
    {
        if (apiKey == null)
        {
            apiKey = AcproConnector.getClient(getUrl()).getApiKey(getUsername(), getPassword(), 28800);
        }
        return new Task[0];/*AcproConnector.getClient(getUrl()).getItems(query, offset, limit, apiKey).stream().peek(a -> logger.warn(a.toString())).map(AcproTask::new)
            .toArray(AcproTask[]::new);*/
    }

    @Override
    public @Nullable CancellableConnection createCancellableConnection()
    {
        return new CancellableConnection()
        {
            @Override
            protected void doTest() throws Exception
            {
                try
                {
                    if (apiKey != null)
                    {
                        return;
                    }

                    apiKey = AcproConnector.getClient(getUrl()).getApiKey(getUsername(), getPassword(), 28800);
                }
                catch (FeignException.Unauthorized e)
                {
                    throw new RuntimeException("Wrong username or password");
                }
                catch (FeignException.FeignClientException e)
                {
                    throw new RuntimeException("Connection failed");
                }
            }

            @Override
            public void cancel()
            {
                // not cancellable
            }
        };
    }

    @Override
    public void initializeRepository()
    {
        logger.info("Initialize repository");
    }
}
