package com.atlassian.webdriver.bitbucket.page;

import com.atlassian.pageobjects.elements.ElementBy;
import com.atlassian.webdriver.bitbucket.element.DiffSelectionDropdown;
import com.atlassian.webdriver.bitbucket.element.SideBySideDiffFileContent;
import com.atlassian.webdriver.bitbucket.util.ElementUtils;
import com.atlassian.webdriver.bitbucket.util.KeyboardShortcuts;
import org.openqa.selenium.By;

public class FileSideBySideDiffPage extends FileContentPage<SideBySideDiffFileContent> {

    @ElementBy(className = "file-content", pageElementClass = SideBySideDiffFileContent.class)
    protected SideBySideDiffFileContent diffContent;

    public FileSideBySideDiffPage(String projectKey, String repoSlug, String path) {
        super(projectKey, repoSlug, path);
    }

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

    @Override
    public SideBySideDiffFileContent getFileContent() {
        return diffContent;
    }

    @Override
    protected String getPathComponent() {
        return "diff";
    }

    @Override
    public FileSideBySideDiffPage loadUntilRevision(String revision) {
        return loadRevision(revision, FileSideBySideDiffPage.class);
    }

    public FileUnifiedDiffPage switchToUnified() {
        pageBinder.bind(DiffSelectionDropdown.class, elementFinder.find(By.id("diff-options-dropdown-trigger"))).open().selectUnified();
        FileUnifiedDiffPage page = pageBinder.bind(FileUnifiedDiffPage.class, projectKey, slug, path);
        page.getFileContent().waitUntilFileContentLoaded();
        return page;
    }

    public void moveToNextChange(boolean expectMovement) {
        navigateDiff(expectMovement, new Runnable() {
            @Override
            public void run() {
                KeyboardShortcuts.moveToNextSecondary(body);
            }
        });
    }

    public void moveToPreviousChange(boolean expectMovement) {
        navigateDiff(expectMovement, new Runnable() {
            @Override
            public void run() {
                KeyboardShortcuts.moveToPreviousSecondary(body);
            }
        });
    }

    private void navigateDiff(boolean expectMovement, final Runnable doNavigation) {
        if (expectMovement) {
            ElementUtils.waitUntilUpdated(getFileContent().find(By.className("content-view")), doNavigation);
        } else {
            doNavigation.run();
        }
    }
}
