package com.atlassian.webdriver.bitbucket.page;

import com.atlassian.pageobjects.elements.ElementBy;
import com.atlassian.webdriver.bitbucket.element.FileBreadcrumbs;
import org.apache.commons.lang3.StringUtils;

public abstract class FileLayoutPage extends BranchLayoutPage {
    protected final String path;
    protected final RevisionSpecifier revisionSpecifier;
    
    public static class RevisionSpecifier {
        public final String at;
        public final String until;

        public RevisionSpecifier(String at, String until) {
            this.until = until;
            this.at = at;
        }
    }

    @ElementBy(className = FileBreadcrumbs.className, pageElementClass = FileBreadcrumbs.class)
    private FileBreadcrumbs breadcrumbs;

    public FileLayoutPage(String projectKey, String repoSlug, String path) {
        this(projectKey, repoSlug, path, null);
    }

    public FileLayoutPage(String projectKey, String repoSlug, String path, RevisionSpecifier revisionSpecifier) {
        super(projectKey, repoSlug);
        this.revisionSpecifier = revisionSpecifier;
        if (!path.isEmpty() && !path.startsWith("/")) {
            this.path = "/" + path;
        } else {
            this.path = path;
        }
    }

    public FileBreadcrumbs getBreadcrumbs() {
        return breadcrumbs;
    }
    
    protected abstract String getPathComponent();

    @Override
    public String getUrl() {
        String qs = "";
        if (revisionSpecifier != null) {
            String at = revisionSpecifier.at;
            String until = revisionSpecifier.until;
            String atQs = StringUtils.isNotBlank(at) ? "at=" + at : "";
            String untilQs = StringUtils.isNotBlank(until) ? "until=" + until : "";
            if (!StringUtils.isBlank(atQs) && !StringUtils.isBlank(untilQs)) {
                qs = "?" + atQs + "&" + untilQs;
            } else if (!StringUtils.isBlank(atQs)) {
                qs = "?" + atQs;
            } else if (!StringUtils.isBlank(untilQs)) {
                qs = "?" + untilQs;
            }
        }
        return "/projects/" + projectKey + "/repos/" + slug + "/" + getPathComponent() + this.path + qs;
    }
}
