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

#import "MainViewController.h"

#import "AuthorizationViewController.h"
#import "HPCredentialsHelper.h"
#import "ReplaceAnimator.h"

@interface MainViewController (MainViewControllerPrivate)

#pragma mark - Private interface

@end

@implementation MainViewController

#pragma mark - View lifecycle

-(void)viewDidLoad {
    [super viewDidLoad];
    self.logoutButtonEnabled = NO;
}

-(void)viewDidAppear {
    HPCredentials *credentials = [[HPCredentialsHelper sharedHelper] getCredentials];
    
    if (credentials.usable == NO) {
        AuthorizationViewController *authorizationViewController = [self.storyboard instantiateControllerWithIdentifier:@"AuthorizationViewController"];
        [self presentViewController:authorizationViewController animator:[[ReplaceAnimator alloc] init]];
    } else {
        self.logoutButtonEnabled = YES;
    }
    
    NSString *instanceURLText = @"";
    if (credentials.baseURL != nil) {
        instanceURLText = credentials.baseURL;
    }

    NSMutableAttributedString *instanceURLValue = [[NSMutableAttributedString alloc] initWithString:instanceURLText];
    if (credentials.baseURL != nil) {
        [instanceURLValue addAttribute:NSLinkAttributeName
                                 value:credentials.baseURL
                                 range:NSMakeRange(0, instanceURLValue.length)];
    }
    [instanceURLValue addAttribute:NSUnderlineStyleAttributeName
                             value:[NSNumber numberWithInteger:NSUnderlineStyleSingle]
                             range:NSMakeRange(0, instanceURLValue.length)];
    
    self.instanceURLLabel.attributedStringValue = instanceURLValue;
}

#pragma mark - Actions

-(IBAction)doLogOut:(id)sender {
    [[HPCredentialsHelper sharedHelper] clearCredentials];
    AuthorizationViewController *authorizationViewController = [self.storyboard instantiateControllerWithIdentifier:@"AuthorizationViewController"];
    [self presentViewController:authorizationViewController animator:[[ReplaceAnimator alloc] init]];
}

@end
