// plugins/wavemaker-screen-security/index.js
const {  withMainActivity, withAppDelegate, withDangerousMod } = require('@expo/config-plugins');
const fs = require('fs');
const path = require('path');


const ANDROID_KOTLIN_SECURITY_MOD_IMPORTS = `import com.facebook.react.ReactActivity\nimport android.view.WindowManager\nimport android.view.ViewGroup\nimport android.view.LayoutInflater`

const ANDROID_KOTLIN_SECURITY_MOD_CLASS_DECLARATION = `class MainActivity : ReactActivity() {
    private var securityView: ViewGroup? = null
`

const ANDROID_KOTLIN_SECURITY_MOD_CONSTRUCTOR = `
        enableSecureFlag()
`

const ANDROID_KOTLIN_SECURITY_MOD_CONTENT = `

    private fun enableSecureFlag() {
        window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
    }
`

const ANDROID_JAVA_SECURITY_MOD_CLASS_DECLARATION = `public class MainActivity extends ReactActivity {
    private ViewGroup securityView = null;
}`

const ANDROID_JAVA_SECURITY_MOD_IMPORTS = `import com.facebook.react.ReactActivity;\nimport android.view.WindowManager;\nimport android.view.ViewGroup;\nimport android.view.LayoutInflater;`

const ANDROID_JAVA_SECURITY_MOD_CONSTRUCTOR = `securityView = (ViewGroup) LayoutInflater.from(this).inflate(
            R.layout.activity_background_security,
            null,
            false
        );
        enableSecureFlag();`

const ANDROID_JAVA_SECURITY_MOD_CONTENT = `
    @Override
    protected void onPause() {
        disableSecureFlag();
        showSecurityView();
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        hideSecurityView();
        enableSecureFlag();
    }

    private void showSecurityView() {
        if (securityView != null) {
            securityView.setVisibility(ViewGroup.VISIBLE);
            addContentView(securityView, new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            ));
        }
    }

    private void hideSecurityView() {
        if (securityView != null) {
            securityView.setVisibility(ViewGroup.GONE);
            ViewGroup rootView = (ViewGroup) getWindow().getDecorView();
            rootView.removeView(securityView);
        }
    }

    private void enableSecureFlag() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
    }

    private void disableSecureFlag() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
    }
`

const modifyKotlinMainActivity = (mainActivity) => {
  // Import the required imports
  if (!mainActivity.contents.includes('import android.view.WindowManager')) {
    mainActivity.contents = mainActivity.contents.replace(
      /import com.facebook.react.ReactActivity/,
      `${ANDROID_KOTLIN_SECURITY_MOD_IMPORTS}`
    );
  }
  
  // Add security view property at class level if not exists
  if (!mainActivity.contents.includes('private var securityView: ViewGroup?')) {
    mainActivity.contents = mainActivity.contents.replace(
      /class MainActivity : ReactActivity\(\) \{/,
      `${ANDROID_KOTLIN_SECURITY_MOD_CLASS_DECLARATION}
       `
    );
  }
  
  // Initialize the security view and enable the secure flag in the constructor.
  if (!mainActivity.contents.includes('enableSecureFlag()')) {
    mainActivity.contents = mainActivity.contents.replace(
      /(override\s+fun\s+onCreate[\s\S]+?\{)([\s\S]*?)(\})/,
      (match, sig, body, endBrace) => `${sig}${body}\n ${ANDROID_KOTLIN_SECURITY_MOD_CONSTRUCTOR}\n${endBrace}`
    )
  }
  
  // Add security methods after onCreate method
  if (!mainActivity.contents.includes('private fun showSecurityView()')) {
    // Find the end of onCreate method and add security methods after it
    mainActivity.contents = mainActivity.contents.replace(
      /(override\s+fun\s+onCreate\s*\([\s\S]*?\)\s*\{[\s\S]*?\})/,
      (match) => `${match}\n${ANDROID_KOTLIN_SECURITY_MOD_CONTENT}`
    );
  }
};

const modifyJavaMainActivity = (mainActivity) => {
  // Import the required imports
  if (!mainActivity.contents.includes('import android.view.WindowManager;')) {
    mainActivity.contents = mainActivity.contents.replace(
      /import com.facebook.react.ReactActivity;/,
      `${ANDROID_JAVA_SECURITY_MOD_IMPORTS}`
    );
  }
  
  // Add security view property at class level if not exists
  if (!mainActivity.contents.includes('private ViewGroup securityView')) {
    mainActivity.contents = mainActivity.contents.replace(
      /public class MainActivity extends ReactActivity \{/,
      `
       ${ANDROID_JAVA_SECURITY_MOD_CLASS_DECLARATION}
       `
    );
  }
  
  // Initialize the security view and enable the secure flag in the constructor.
  if (!mainActivity.contents.includes('enableSecureFlag()')) {
    mainActivity.contents = mainActivity.contents.replace(
      /(protected\s+void\s+onCreate[\s\S]+?\{)([\s\S]*?)(\})/,
      (match, sig, body, endBrace) => `${sig}${body}\n        ${ANDROID_JAVA_SECURITY_MOD_CONSTRUCTOR}\n    ${endBrace}`
    )
  }
  
  // Add security methods after onCreate method
  if (!mainActivity.contents.includes('private void showSecurityView()')) {
    // Find the end of onCreate method and add security methods after it
    mainActivity.contents = mainActivity.contents.replace(
      /(protected\s+void\s+onCreate\s*\([\s\S]*?\)\s*\{[\s\S]*?\})/,
      (match) => `${match}\n${ANDROID_JAVA_SECURITY_MOD_CONTENT}`
    );
  }
};

const IOS_APP_DELEGATE_MODIFICATIONS = `

- (void)applicationWillResignActive:(UIApplication *)application {
    [self showWavemakerSecurityOverlay];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [self hideWavemakerSecurityOverlay];
}

- (void)showWavemakerSecurityOverlay {
    if (self.wavemakerSecurityOverlay) return;
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (!window) window = [[[UIApplication sharedApplication] windows] firstObject];
    
    if (window) {
        self.wavemakerSecurityOverlay = [[UIView alloc] initWithFrame:window.bounds];
        self.wavemakerSecurityOverlay.backgroundColor = [UIColor whiteColor];
        
        // Add your WaveMaker branding or generic security message
        UIImageView *logoView = [[UIImageView alloc] init];
        // You can add WaveMaker logo here
        
        UILabel *label = [[UILabel alloc] init];
        label.text = @"🔒 Application Secured";
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:20 weight:UIFontWeightMedium];
        label.translatesAutoresizingMaskIntoConstraints = NO;
        
        [self.wavemakerSecurityOverlay addSubview:label];
        [NSLayoutConstraint activateConstraints:@[
            [label.centerXAnchor constraintEqualToAnchor:self.wavemakerSecurityOverlay.centerXAnchor],
            [label.centerYAnchor constraintEqualToAnchor:self.wavemakerSecurityOverlay.centerYAnchor]
        ]];
        
        [window addSubview:self.wavemakerSecurityOverlay];
        [window bringSubviewToFront:self.wavemakerSecurityOverlay];
    }
}

- (void)hideWavemakerSecurityOverlay {
    [self.wavemakerSecurityOverlay removeFromSuperview];
    self.wavemakerSecurityOverlay = nil;
}
`;

const withWavemakerScreenSecurity = (config, options = {}) => {
  const { 
    enableAndroidFlagSecure = true,
    enableiOSBackgroundOverlay = true,
    overlayMessage = "Application Secured",
    overlayBackgroundColor = "#FFFFFF"
  } = options;

if (enableAndroidFlagSecure) {
  copyAndroidLayoutFile(config);
  
  config = withMainActivity(config, (config) => {
    const mainActivity = config.modResults;
    const isKotlin = mainActivity.path.endsWith('.kt');
    
    isKotlin ? modifyKotlinMainActivity(mainActivity) : modifyJavaMainActivity(mainActivity);
    
    return config;
  });


}

  if (enableiOSBackgroundOverlay) {
    config = withAppDelegate(config, (config) => {
      const appDelegate = config.modResults;
      
      if (!appDelegate.contents.includes('#import <UIKit/UIKit.h>') && !appDelegate.contents.includes('@import UIKit;')) {
        appDelegate.contents = appDelegate.contents.replace(
          /#import "AppDelegate.h"/,
          `#import "AppDelegate.h"\n#import <UIKit/UIKit.h>`
        );
      }
      
      if (!appDelegate.contents.includes('wavemakerSecurityOverlay')) {
        appDelegate.contents = appDelegate.contents.replace(
          /@implementation AppDelegate/,
          `@interface AppDelegate ()\n@property (nonatomic, strong) UIView *wavemakerSecurityOverlay;\n@end\n\n@implementation AppDelegate`
        );
      }
      
      if (!appDelegate.contents.includes('showWavemakerSecurityOverlay')) {
        // Find the last @end and add methods before it
        const lastEndIndex = appDelegate.contents.lastIndexOf('@end');
        if (lastEndIndex !== -1) {
          appDelegate.contents = 
            appDelegate.contents.substring(0, lastEndIndex) + 
            IOS_APP_DELEGATE_MODIFICATIONS + 
            '\n\n@end' + 
            appDelegate.contents.substring(lastEndIndex + 4);
        }
      }
            
      return config;
    });
  }

  return config;
};

const copyAndroidLayoutFile = (config) => {
  config = withDangerousMod(config, ['android', async (config) => {
    const projectRoot = config.modRequest.projectRoot;
    const sourceLayoutPath = path.join(__dirname, 'activity_background_security.xml');
    const targetLayoutDir = path.join(projectRoot, 'android', 'app', 'src', 'main', 'res', 'layout');
    const targetLayoutPath = path.join(targetLayoutDir, 'activity_background_security.xml');

    if (!fs.existsSync(targetLayoutDir)) {
      fs.mkdirSync(targetLayoutDir, { recursive: true });
    }

    if (fs.existsSync(sourceLayoutPath)) {
      fs.copyFileSync(sourceLayoutPath, targetLayoutPath);
    } else {
      console.warn('Source layout file not found:', sourceLayoutPath);
    }
    return config;
  }])
};

module.exports = withWavemakerScreenSecurity;