//
//  MainViewController.m
//  HotPocket (iOS)
//
//  Created by Tomek Wójcik on 25/09/2025.
//

#import "MainViewController.h"

#import "AuthorizationViewController.h"
#import "HPCredentialsHelper.h"
#import "NSBundle+HotPocketExtensions.h"
#import "UnameLabel.h"

@interface MainViewController (MainViewControllerPrivate)

#pragma mark - Private interface

@end

@implementation MainViewController

#pragma mark - View lifecycle

-(void)viewDidLoad {
    [super viewDidLoad];
    
    [self.instanceURLButton setTitle:@"" forState:UIControlStateNormal];
    self.instanceURLButton.enabled = NO;
    
    self.unameLabel.text = [NSBundle uname];
    
    self.logoutButton.enabled = NO;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];

    HPCredentials *credentials = [[HPCredentialsHelper sharedHelper] getCredentials];
    if (credentials.usable == NO) {
        AuthorizationViewController *authorizationViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"AuthorizationViewController"];
        [self.navigationController pushViewController:authorizationViewController animated:NO];
    } else {
        [self.instanceURLButton setTitle:credentials.baseURL forState:UIControlStateNormal];
        self.instanceURLButton.enabled = YES;

        self.logoutButton.enabled = YES;
    }
    
    NSString *instanceURLText = @"";
    if (credentials.baseURL != nil) {
        instanceURLText = credentials.baseURL;
    }
    
    self.instanceURLButton.titleLabel.text = instanceURLText;
}

#pragma mark - Actions

-(IBAction)doOpenInstanceURL:(id)sender {
    HPCredentials *credentials = [[HPCredentialsHelper sharedHelper] getCredentials];
    if (credentials.usable == YES) {
        NSURL *instanceURL = [NSURL URLWithString:credentials.baseURL];
        
        UIApplication *application = [UIApplication sharedApplication];
        if ([application canOpenURL:instanceURL] == YES) {
            [application openURL:instanceURL options:@{} completionHandler:nil];
        }
    }
}

-(IBAction)doLogOut:(id)sender {
    [[HPCredentialsHelper sharedHelper] clearCredentials];
    
    AuthorizationViewController *authorizationViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"AuthorizationViewController"];
    [self.navigationController pushViewController:authorizationViewController animated:NO];
}

@end
