package com.atlassian.webdriver.bitbucket.page;

import com.atlassian.webdriver.bitbucket.element.FileContent;
import com.atlassian.webdriver.bitbucket.element.RevisionHistoryDialog;
import org.openqa.selenium.By;

public abstract class FileContentPage<T extends FileContent> extends FileLayoutPage implements HasRevisionPicker {

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

    public FileContentPage(String projectKey, String repoSlug, String path, RevisionSpecifier revisionSpecifier) {
        super(projectKey, repoSlug, path, revisionSpecifier);
    }

    @Override
    public void doWait() {
        super.doWait();
        getFileContent().waitUntilPageLoaded();
    }

    public String getCurrentRevisionAuthor() {
        return driver.findElement(By.cssSelector(".commit-badge-container .commit-author")).getText();
    }

    public String getCurrentRevisionDate() {
        return driver.findElement(By.cssSelector(".commit-badge-container time")).getText();
    }

    public String getCurrentRevisionId() {
        return driver.findElement(By.cssSelector(".commit-badge-container .commitid")).getText();
    }

    public String getCurrentRevisionMachineDate() {
        return driver.findElement(By.cssSelector(".commit-badge-container time")).getAttribute("datetime");
    }

    public abstract T getFileContent();

    @Override
    public RevisionHistoryDialog getRevisionHistoryDialog() {
        return pageBinder.bind(RevisionHistoryDialog.class);
    }

    protected <P> P loadRevision(String revision, Class<P> pageClass) {
        getRevisionHistoryDialog().clickItemAndWaitForClose(revision.substring(0, 11));

        return pageBinder.bind(pageClass, projectKey, slug, path, new RevisionSpecifier(null, revision));
    }
}
