import { deepLinkHandlerSnippet } from "./iosConstants";
import { SmartechBaseProps } from "./smartechBaseProps";
import { promises as fs } from 'fs';
import path from 'path';


export class Helper {

    static Ios = class {

        static addDeepLinkHandler(content: string, props: SmartechBaseProps): string {
            const smartechContentLines = content.split("\n");
            const lastLine = this.getLastLine(smartechContentLines);
            const deepLinkHandlerLines = deepLinkHandlerSnippet(props.deepLinkDelay);

            const smartechDelegateContents = [
                ...smartechContentLines.slice(0, lastLine + 1),
                deepLinkHandlerLines,
                ...smartechContentLines.slice(lastLine + 1),
            ].join("\n");

            return smartechDelegateContents;
        };

        static getLastLine = (lineArray: string[]): number => {
            return lineArray.lastIndexOf("@end") - 1;
        };

        // Utility function to detect if project uses Swift
        static isSwiftProject = async (platformProjectRoot: string, projectName: string): Promise<boolean> => {
            try {
                const appDelegateSwiftPath = path.join(platformProjectRoot, projectName, 'AppDelegate.swift');
                await fs.access(appDelegateSwiftPath);
                return true;
            } catch {
                return false;
            }
        };

        // Utility function to get the correct AppDelegate file path for Objective-C projects
        static getObjCAppDelegatePath = async (platformProjectRoot: string, projectName: string): Promise<string> => {
            const appDelegateMmPath = path.join(platformProjectRoot, projectName, 'AppDelegate.mm');
            const appDelegateMPath = path.join(platformProjectRoot, projectName, 'AppDelegate.m');

            try {
                await fs.access(appDelegateMmPath);
                return appDelegateMmPath;
            } catch {
                return appDelegateMPath; // Fallback to .m even if it doesn't exist
            }
        };
    }

    static Android = class {

        static addDependency(appContents: string,
            dependency: string,
            version: string): string {
            const dependencyTemplate = `api "${dependency}:${version}"`;
            return appContents.replace('dependencies {', `dependencies {\n  ${dependencyTemplate}`);
        }
    }
}

