#!/bin/bash

# 이전 스플래시 화면 설정으로 복원하는 스크립트
echo "이전 스플래시 화면 설정으로 복원 중..."

# 프로젝트 디렉토리로 이동
cd "$(dirname "$0")"

# 1. ViewController.swift 복원
echo "ViewController.swift 복원 중..."
VIEWCONTROLLER="ios/App/App/ViewController.swift"

if [ -f "${VIEWCONTROLLER}.bak_duration" ]; then
  # 백업에서 복원
  cp "${VIEWCONTROLLER}.bak_duration" "$VIEWCONTROLLER"
  echo "ViewController.swift를 이전 버전으로 복원했습니다."
else
  # 백업이 없는 경우 직접 작성
  cat > "$VIEWCONTROLLER" << 'EOL'
import UIKit
import Capacitor
import WebKit

class ViewController: CAPBridgeViewController {
    
    private var splashView: UIView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 스플래시 뷰 생성
        setupSplashView()
        
        // 웹뷰 로드 완료 감지
        NotificationCenter.default.addObserver(self, selector: #selector(webViewDidFinishLoad), name: NSNotification.Name(rawValue: "capacitorWebViewDidLoad"), object: nil)
    }
    
    private func setupSplashView() {
        // 스플래시 뷰 생성
        splashView = UIView(frame: self.view.bounds)
        splashView?.backgroundColor = UIColor.white
        
        // 스플래시 이미지 추가
        let imageView = UIImageView(image: UIImage(named: "Splash"))
        imageView.contentMode = .scaleAspectFit
        imageView.translatesAutoresizingMaskIntoConstraints = false
        
        if let splashView = splashView {
            self.view.addSubview(splashView)
            splashView.addSubview(imageView)
            
            NSLayoutConstraint.activate([
                imageView.centerXAnchor.constraint(equalTo: splashView.centerXAnchor),
                imageView.centerYAnchor.constraint(equalTo: splashView.centerYAnchor),
                imageView.widthAnchor.constraint(equalToConstant: 200),
                imageView.heightAnchor.constraint(equalToConstant: 200)
            ])
        }
    }
    
    @objc private func webViewDidFinishLoad() {
        // 웹뷰 로드 완료 시 스플래시 화면 제거 (2초 후)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            UIView.animate(withDuration: 0.3, animations: {
                self.splashView?.alpha = 0
            }, completion: { _ in
                self.splashView?.removeFromSuperview()
                self.splashView = nil
            })
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // 웹뷰 로드 시작 시 스크립트 실행 (최대 2초 후 스플래시 제거)
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            if self.splashView != nil && self.splashView?.alpha == 1 {
                UIView.animate(withDuration: 0.3, animations: {
                    self.splashView?.alpha = 0
                }, completion: { _ in
                    self.splashView?.removeFromSuperview()
                    self.splashView = nil
                })
            }
        }
    }
}
EOL
  echo "ViewController.swift를 재생성했습니다."
fi

# 2. AppDelegate.swift 복원
echo "AppDelegate.swift 복원 중..."
APP_DELEGATE="ios/App/App/AppDelegate.swift"

if [ -f "${APP_DELEGATE}.bak_bgcolor" ]; then
  # 백업에서 복원
  cp "${APP_DELEGATE}.bak_bgcolor" "$APP_DELEGATE"
  echo "AppDelegate.swift를 이전 버전으로 복원했습니다."
else
  # 백업이 없는 경우 직접 작성
  cat > "$APP_DELEGATE" << 'EOL'
import UIKit
import Capacitor
import WebKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 웹뷰 캐시 설정 최적화
        let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
        let date = Date(timeIntervalSince1970: 0)
        WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date, completionHandler:{ })
        
        // 웹뷰 설정 최적화
        let webViewConfig = WKWebViewConfiguration()
        webViewConfig.allowsInlineMediaPlayback = true
        webViewConfig.suppressesIncrementalRendering = false
        webViewConfig.allowsAirPlayForMediaPlayback = true
        webViewConfig.mediaTypesRequiringUserActionForPlayback = []
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        // Called when the app was launched with a url. Feel free to add additional processing here,
        // but if you want the App API to support tracking app url opens, make sure to keep this call
        return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
    }

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // Called when the app was launched with an activity, including Universal Links.
        // Feel free to add additional processing here, but if you want the App API to support
        // tracking app url opens, make sure to keep this call
        return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
    }

}
EOL
  echo "AppDelegate.swift를 재생성했습니다."
fi

# 3. capacitor.config.ts 복원
echo "capacitor.config.ts 복원 중..."
if [ -f "capacitor.config.ts.bak" ]; then
  # 백업에서 복원
  cp "capacitor.config.ts.bak" "capacitor.config.ts"
  echo "capacitor.config.ts를 이전 버전으로 복원했습니다."
else
  # 백업이 없는 경우 직접 작성
  cat > "capacitor.config.ts" << 'EOL'
import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  appId: 'com.lovable.zellyfinance',
  appName: '젤리의 적자탈출',
  webDir: 'dist',
  server: {
    androidScheme: 'https',
    iosScheme: 'https',
    cleartext: true
  },
  plugins: {
    SplashScreen: {
      launchShowDuration: 3000,
      launchAutoHide: true,
      backgroundColor: "#FFFFFF",
      androidSplashResourceName: "splash",
      androidScaleType: "CENTER_CROP",
      showSpinner: false,
      splashFullScreen: false,
      splashImmersive: false
    },
    Keyboard: {
      resize: "body",
      style: "dark",
      resizeOnFullScreen: true
    }
  },
  ios: {
    scheme: "App"
  }
};

export default config;
EOL
  echo "capacitor.config.ts를 재생성했습니다."
fi

# 4. index.html 복원 (웹뷰 로드 완료 알림 코드 제거)
echo "index.html 복원 중..."
INDEX_HTML="ios/App/App/public/index.html"

if [ -f "${INDEX_HTML}.bak_bgcolor" ]; then
  # 백업에서 복원
  cp "${INDEX_HTML}.bak_bgcolor" "$INDEX_HTML"
  echo "index.html을 이전 버전으로 복원했습니다."
else
  echo "index.html 백업을 찾을 수 없습니다. 수동으로 확인이 필요합니다."
fi

# 5. Info.plist 복원
echo "Info.plist 복원 중..."
INFO_PLIST="ios/App/App/Info.plist"

if [ -f "${INFO_PLIST}.bak_force" ]; then
  # 백업에서 복원
  cp "${INFO_PLIST}.bak_force" "$INFO_PLIST"
  echo "Info.plist를 이전 버전으로 복원했습니다."
else
  echo "Info.plist 백업을 찾을 수 없습니다. 수동으로 확인이 필요합니다."
fi

# 6. LaunchScreen.storyboard 복원
echo "LaunchScreen.storyboard 복원 중..."
cat > ios/App/App/Base.lproj/LaunchScreen.storyboard << 'EOL'
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17156" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
    <device id="retina4_7" orientation="portrait" appearance="light"/>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17126"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="EHf-IW-A2E">
            <objects>
                <viewController id="01J-lp-oVM" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="Splash" translatesAutoresizingMaskIntoConstraints="NO" id="hLz-g1-Xcm">
                                <rect key="frame" x="87.5" y="233.5" width="200" height="200"/>
                                <constraints>
                                    <constraint firstAttribute="width" constant="200" id="Zmm-k7-Wvl"/>
                                    <constraint firstAttribute="height" constant="200" id="zrV-nL-Fgq"/>
                                </constraints>
                            </imageView>
                        </subviews>
                        <viewLayoutGuide key="safeArea" id="Bcu-3y-fUS"/>
                        <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                        <constraints>
                            <constraint firstItem="hLz-g1-Xcm" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="Jgv-Jh-bz9"/>
                            <constraint firstItem="hLz-g1-Xcm" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="YPE-Yx-CnE"/>
                        </constraints>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="53" y="375"/>
        </scene>
    </scenes>
    <resources>
        <image name="Splash" width="200" height="200"/>
    </resources>
</document>
EOL

# 7. Capacitor 설정 동기화
echo "Capacitor 설정 동기화 중..."
npx cap sync ios

echo "완료! 이제 Xcode에서 다시 빌드하세요."
