package com.huangzj.protoplugin.memo;

import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.project.Project;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.jetbrains.annotations.NotNull;

@State(name = "ProtoPluginMemos", storages = @Storage("protoPluginMemos.xml"))
public final class MemoProjectService implements PersistentStateComponent<MemoProjectService.State> {

    public static MemoProjectService getInstance(@NotNull Project project) {
        return project.getService(MemoProjectService.class);
    }

    public static final class State {
        public List<MemoItem> items = new ArrayList<>();
        /** 见 {@link MemoUiTheme#getPersistenceId()} */
        public String memoThemeId = MemoUiTheme.IDE_DEFAULT.getPersistenceId();
    }

    private State state = new State();

    @NotNull
    @Override
    public State getState() {
        return state;
    }

    @Override
    public void loadState(@NotNull State loaded) {
        this.state = loaded;
        if (this.state.items == null) {
            this.state.items = new ArrayList<>();
        }
        if (this.state.memoThemeId == null || this.state.memoThemeId.isEmpty()) {
            this.state.memoThemeId = MemoUiTheme.IDE_DEFAULT.getPersistenceId();
        }
    }

    public List<MemoItem> getItems() {
        return state.items;
    }

    public MemoItem createMemo() {
        MemoItem m = new MemoItem();
        m.id = UUID.randomUUID().toString();
        m.title = "";
        m.content = "";
        m.updated = System.currentTimeMillis();
        state.items.add(m);
        return m;
    }

    public void removeById(@NotNull String id) {
        for (Iterator<MemoItem> it = state.items.iterator(); it.hasNext(); ) {
            MemoItem m = it.next();
            if (id.equals(m.id)) {
                it.remove();
                return;
            }
        }
    }

    public MemoItem findById(@NotNull String id) {
        for (MemoItem m : state.items) {
            if (id.equals(m.id)) {
                return m;
            }
        }
        return null;
    }

    @NotNull
    public MemoUiTheme getMemoTheme() {
        return MemoUiTheme.fromPersistenceId(state.memoThemeId);
    }

    public void setMemoTheme(@NotNull MemoUiTheme theme) {
        state.memoThemeId = theme.getPersistenceId();
    }
}
