//
//  PiTestBase.swift
//  PiUITests
//
//  Created by Aravind Sudharsan on 1/20/21.
//
//  Contains the generic helper functions used for the various UI tests

import Foundation
import XCTest

class PiTestBase: XCTestCase {

    var app = XCUIApplication()
    let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
    let deleteUser = DeleteUserUtility()
    var user = User()
    /// This is optional. Tests must be intentional in giving it a value
    var isWatchPaired: Bool?

    /*
     * This allows in resetting the state of the app between tests, forcing the user to login again
     */
    var shouldReset: Bool {
        return false
    }
    
    /*
     * This allows to delete the app
     */
    var deleteApp: Bool {
        return false
    }
    
    /*
     * Variables for getting the iOS version of the current device and device name
     */
    let iOSVersion = UIDevice.current.systemVersion
    let iOSDeviceName = UIDevice.current.name
    
    override func setUp() {
        if deleteApp {
            deleteInstalledApp(PiTestConfig.APP_NAME)
        }
        super.setUp()
        continueAfterFailure = false
        if let paired = isWatchPaired {
            app.launchEnvironment["isWatchPaired"] = String(describing: paired)
        }
        app.launchArguments = shouldReset ? ["--Reset"] : []
        app.launch()
    }

    override func tearDown() {
        app.terminate()
        if user.getUUID() != "" || user.getUserId() != 0 {
            deleteUser.deleteUser(userId: String(user.getUserId()))
        }
        super.tearDown()
    }
    
    /*
     * Function for deleting the app
     */
    func deleteInstalledApp(_ appName: String) {
        // Force delete the Pascal app from the springboard. Activating spring board and finding the icon
        app.terminate()
        springboard.activate()
        let icon = springboard.icons[appName]
        if icon.exists {
            icon.press(forDuration: 5.0)
            // The first time app gets installed and deleted, an alert comes in iOS 14 which needs to be handled
            if (springboard.alerts["Edit Home Screens"].buttons["OK"].waitForExistence(timeout: 10)) {
                springboard.alerts["Edit Home Screens"].buttons["OK"].tap()
            }
            BasePage(application: app).waitForElementToExist(element: icon.buttons["DeleteButton"], timeout: 10)
            icon.buttons["DeleteButton"].tap()
            if (iOSVersion >= "14.0" && iOSVersion <= "14.0.1") {
                if springboard.staticTexts[PiTestConfig.DELETE_APP_IOS_14_0_1].waitForExistence(timeout: 10) {
                    springboard.buttons["Delete App"].tap()
                }
            } else {
                if springboard.staticTexts[PiTestConfig.DELETE_APP_OTHER].waitForExistence(timeout: 10) {
                    springboard.buttons["Delete App"].tap()
                }
            }

            // Dismissing the alert after pressing delete icon
            let popupAlert = springboard.alerts.buttons["Delete"]
            XCTAssert(popupAlert.waitForExistence(timeout: 2))
            popupAlert.tap()
            XCUIDevice.shared.press(.home)
            XCUIDevice.shared.press(.home)
        }
        // If the icon is not found
        else {
            print("PiTestBase-deleteInstalledApp: Warning: Could not find app called \(appName)")
        }
    }
}
