//
//  MainViewControllerReplace.m
//  Disst
//
//  Created by 전정철 on 2020/10/26.
//

#import "MainViewControllerReplace.h"
#import <CoreLocation/CoreLocation.h>

@interface MainViewControllerReplace()
@property (nonatomic, strong) CLLocationManager *locationManager;
@end

@implementation MainViewControllerReplace
- (void)loadView
{
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
    
	NSLog(@"view did load");
	// [NSURL *url] = [NSURL URLWithString:"https://safecity.seoul.go.kr/disstResp"];
	// [NSURLRequest *request] = [NSURLRequest requestWithURL:url];
    
}

#pragma mark WKWebViewDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"확인" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alertController animated:true completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"확인" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(true);
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"취소" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(false);
    }]];
    [self presentViewController:alertController animated:true completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:prompt preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text= defaultText;
    }];
    [alertController addAction:[UIAlertAction actionWithTitle:@"확인" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (alertController.textFields != nil &&
            alertController.textFields.firstObject != nil) {
            NSString *text = alertController.textFields.firstObject.text;
            completionHandler(text);
        } else {
            completionHandler(defaultText);
        }
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"취소" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(nil);
    }]];
    [self presentViewController:alertController animated:true completion:nil];
}

/**
 * 쿠키 세팅을 통한 Session 유지
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)[navigationResponse response];
    if (urlResponse == nil) {
        NSLog(@"EXIT : no resp found");
        return;
    }
    
    NSURL *url = urlResponse.URL;
    NSDictionary *allHeaderFields = (NSDictionary<NSString *, NSString *> *)urlResponse.allHeaderFields;
    NSArray<NSHTTPCookie *> *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:allHeaderFields forURL:url];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:url mainDocumentURL:nil];
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSString *curUrl = navigationAction.request.URL.absoluteString;
    
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    
    if (![curUrl containsString:@"fileId"]) {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    
    NSLog(@"fileId가 포함됨");
    
    NSString *decode = curUrl.stringByRemovingPercentEncoding;
//    NSLog(@"filename : {0}", [curUrl fileName]);
//    NSLog(@"file extension : {0}", [curUrl fileExtension]);
    NSLog(@"decode : %@", decode);
    NSArray<NSString *> *split = [curUrl componentsSeparatedByString:@"="];
    NSString *fileName = [split valueForKey:@"@lastObject"];
    NSLog(@"fileName : %@", fileName);
    
    NSData *data = [NSData dataWithContentsOfURL:navigationAction.request.URL];
    if (data==nil) {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    NSString *paths =
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)[0];
    NSLog(@"paths: %@", paths);
    
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",paths,fileName];
    NSLog(@"filePath: %@", filePath);
    
    [data writeToFile:filePath atomically:true];
    NSLog(@"download success");
    
    decisionHandler(WKNavigationActionPolicyAllow);
}


#pragma mark WKWebViewDelegate

@end
